Refresh img at some interval - javascript

I have following div inside my jsp file
<div id="myDiv">
<img alt="" src="http://localhost:8080/chartDemo/servlet/ChartDemoServlet">
</div>
I want to automatically refresh the image at some interval.
I have tried with <meta http-equiv="Refresh"> it works perfect but refreshes the whole page.
How do I refresh only the image?

I want to automatically refresh that div at some interval.
With what content? Or does the img change every time?
If so:
setInterval(function() {
$("#myDiv").html('<img alt="" src="http://localhost:8080/chartDemo/servlet/ChartDemoServlet">');
}, 1000);
...should do it, once a second (1000ms = 1 second), provided the cache headers on the data returned by the img's src URL are correct (otherwise, the browser may cache the earlier version). What that does is completely tear down the contents of the div, and then assign the given markup to it, which should recreate the img element and cause a re-fetch (again, provided the headers are right).

setInterval(function() {
// use to prevent browser cache
var d = new Date();
$("#myDiv img").attr("src", "http://localhost:8080/chartDemo/servlet/ChartDemoServlet?"+d.getTime());
}, 3000); // every 3 seconds.

<div id="myDiv" onload="JavaScript:timedRefresh(5000);">
<img alt=""
src="http://localhost:8080/chartDemo/servlet/ChartDemoServlet">
</div>
put it in javascript
function timedRefresh(timeoutPeriod) {
setTimeout("location.reload(true);",timeoutPeriod);
}

You need to use window.setInterval timer. In that function you give change the img src.
soemthing like this
//timer function
window.setInterval(refreshImage,1000);
function refreshImage()
{
$('#urdiveid img').attr('src')='new location';
}

It can be done with JavaScript Timeout Function
var t=setTimeout("functiontoCall()", 3000)
You can write your own in FunctiontoCall() to load content in myDiv. It can be ajax call or simple Dom Manipulation

Related

Why does onload cause my image switch to flicker?

For some reason, when I use the attribute onload on my img tag, it causes my images to flicker. Ideally, when I load the page, an image is displayed and when I refresh the page, the image is changed.
Here's my tag as well as the function for it:
HTML
<img id="randomimage" onload="randomImg()" src="images/carmainpic.jpg" alt="main pic of car"/>
JavasScript
function randomImg(){
var images=["images/carmainpic.jpg","images/carmainpic2.jpg","images/carmainpic3.jpg"];
var num=Math.floor(Math.random()*3);
document.getElementById("randomimage").src=images[num];
}
Because the function you're calling changes the image's src to a random pick from the array, triggering a new load event, which changes the src randomly again, etc. On at least some browsers the cycle probably stops when you happen to assign the URL the image already has, too.
If your goal is to just show one of those images, at random, you can do that by leaving src off the img entirely and then adding it (once) with script (either immediately following the img in order to avoid your layout having to be adjusted when you add it, or in script at the end of the page if you prefer; no need to wait for any event):
<img id="randomimage" alt="main pic of car"/>
<script>
(function() {
var images=["images/carmainpic.jpg","images/carmainpic2.jpg","images/carmainpic3.jpg"];
var num=Math.floor(Math.random() * images.length); // <== Note change, so adding images to the array Just Works
document.getElementById("randomimage").src=images[num];
})();
</script>
Even if you put the script immediately after the <img ...> tag, the img element will be available to the script. So your choice whether to do it inline or with the other scripts at the end of the page.
The randomImg function is called every time the image loads. You can use a flag variable to make sure that you only change the image once:
var changed = false;
function randomImg(){
if (!changed) {
changed = true;
var images=["images/carmainpic.jpg","images/carmainpic2.jpg","images/carmainpic3.jpg"];
var num=Math.floor(Math.random()*3);
document.getElementById("randomimage").src=images[num];
}
}
The problem is that you are listening to the load event on the image, instead of the page.
onload="randomImg()"
So, as soon as the first image loads, it triggers the function randomImg which causes change of src attribute on the image. So the browser will attempt to assign a new image to the element, and yet another load event is triggered, which repeats the entire cycle.
Instead, if you want to choose a random image when the page loads, you can listen to DOMContentLoaded event on the document, and choose a random image.
document.addEventListener("DOMContentLoaded", function() {
var images=["images/carmainpic.jpg","images/carmainpic2.jpg","images/carmainpic3.jpg"];
var num=Math.floor(Math.random()*3);
document.getElementById("randomimage").src=images[num];
console.log("Showing: " + images[num]);
});
<img id="randomimage" src="images/carmainpic.jpg" alt="main pic of car"/>
Note: Since you are selecting a random image, it is not guaranteed that you will always get a different image when the page is refreshed. Instead, if you must get a different image on refreshing the page, you can perhaps persist the image identifier in localStorage, and use that to determine the next image to display.
Well you can use $(document).ready(function(){}) to do that. Because you want when charge the page that function execute it.
$(document).ready(function(){
function randomImg(){
var images=["https://www.bensound.com/bensound-img/romantic.jpg","https://www.psdstack.com/wp-content/uploads/2016/10/featured-copyright-free-mages.jpg","http://shaebaxter.com/wp-content/uploads/2015/04/Life-of-Pix-free-stock-photos-sea-peaople-water-waves-back-Sunset-Joshua-earle-1024x682.jpg"];
var num=Math.floor(Math.random()*3);
document.getElementById("randomimage").src=images[num];
}
randomImg();
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<img id="randomimage" src="" alt="main pic of car"/>

"Starting" iframe without changing html content

Here is my problem:
I have threes iframes, with some kind of content. I need to "start" them with for example 1 sec interval. But! I can't change content of html file at all (i have content watcher that refreshes page after any change of file)
Is there any possibility to delay serving contents of iframes?
Of course something like that: jQuery .ready in a dynamically inserted iframe or that: Load iFrame after page load or anything i could find here doesnt work.
Don't give them an src and use a data attribute instead
<iframe data-src="http://google.com"></iframe>
Then loop over them and set the src based on whatever interval you want
var frameInterval = 1000;
$('iframe').each(function(index){
var $frame = $(this), src = $frame.data('src');
setTimeout(function(){
$frame.attr('src', src);
}, index * frameInterval );
});
The comments in question about content watcher are not clear enough to understand what that issue means with regard to this situation

How to change images when a later one becomes available in javascript [duplicate]

This question already has an answer here:
JavaScript Image onload event binding
(1 answer)
Closed 8 years ago.
I am displaying some thumbnails which periodically get regenerated by an external process on the server. I want to display a spinner (gif) on the ones that are currently missing when the page loads, and replace the spinners with their thumbnails when they eventually arrive. Displaying a spinner is trivial. The thumbnail filenames are all known in advance. I haven't been able to figure out a way to watch for them to show up in Javascript.
It can be many minutes until some of the thumbnails get created. The process that creates them deletes them just before it does new processing which results in a new thumbnail. The interval between these external processing episodes can be hours.
Can anyone think of a way to do this? (no Ajax or Jquery - just basic Javascript).
Thanks.
EDIT - I'm sure this could be improved but it seems to work. Thanks for the hints and suggestions. It gave me the idea I was looking for. Someone with the ability to do so might want to remove the note at the top about this question already being answered with the link - that question is not relevant. --JKC
var intervalId, thumbs;
function refresh_thumbs() {
// Refresh whether they need it or not. If the thumb isn't there,
// onerror will (re)load the spinner.
for (i=0; i<thumbs.length; i++) {
id = "snap_"+i;
document.getElementById(id).src = thumbs[i];
}
}
function init(thumbstring) {
// Split comma-separated string into an array of thumbnail links
thumbs=thumbstring.split(",");
refresh_thumbs();
intervalId = window.setInterval( refresh_thumbs, 5000); // milliseconds
}
As an example, one page might be generated containing the following:
<img src='/d/thumb_0.png' id='snap_0' onerror='this.src="/s/spinner.gif";'>
<img src='/d/thumb_1.png' id='snap_1' onerror='this.src="/s/spinner.gif";'>
<script>
init("/d/thumb_0.png,/d/thumb_1.png");
</script>
Calling refresh_thumbs before setInterval is necessary to prevent having to wait 5 seconds to see the thumbs which are there to begin with.
I have a suspicion I don't need the intervalId saved for any reason.
Use setInterval to periodically change the src of the images that are waiting. You can append a query string to the image URL in the form of a timestamp to prevent caching. Not sure how you detect if an image is ready or not this way, but I'm sure that's easy to figure out with some trial and error.
Update: onerror triggers for each unreachable URL you set. Keep polling URLs with new timestamps until you stop receiving errors (that means the image is ready).
Update: I played around with this problem trying to find a general solution. Here's what I came up with:
HTML:
<body style="background-color: #CCC;">
<img src="/img/fail.png" width=200 onerror="imgErr(this);" />
<img src="/img/fail.png" width=200 onerror="imgErr(this);" />
<img src="/img/fail.png" width=200 onerror="imgErr(this);" />
<img src="/img/fail.png" width=200 onerror="imgErr(this);" />
<img src="/img/fail.png" width=200 onerror="imgErr(this);" />
<img src="/img/fail.png" width=200 onerror="imgErr(this);" />
</body>
JS:
var imgElems = [],
imgUrls = [];
function imgErr(img) {
imgElems.push(img);
//imgUrls.push(img.src); // <-- real code
imgUrls.push('/img/logo.png'); // <-- literal url for testing
}
onload = function () {
var interval,
timeout = 3000,
time,
url,
img;
interval = setInterval(function () {
time = new Date().getTime();
while (imgElems.length) {
img = imgElems.shift();
url = imgUrls.shift();
img.src = url + '?time=' + time;
}
}, timeout);
}
JSFiddle
If I'm understanding correctly, your issue isn't knowing when the image loads; your issue is that you can't issue a request for the image because it may take hours to load. So when you set the src, it times out, and that's all the information you get.
You have a few choices.
Perhaps the easiest way to get the file is continuously attempt to reload each image. In that case, you're close, though you'll want a separate div with the spinner to show while waiting:
<img src='spinner.gif' id='spinner' />
<img src='thumb.png' id='thumb' />
document.getElementById("thumb").onload = function() {
document.getElementById("spinner").style[display] = "hidden";
}
document.getElementById("thumb").onerror = function() {
this.src = "thumb.png";
}
You'd need to tweak the positioning, but this will make a spinner, make it disappear when the image loads, and attempt to reload it when the image is not yet ready.
The other alternative I was going to suggest has already been suggested by Jo Are By - set an interval every few minutes to reset the source of the images. There are lots of variations you can do here (reset all sources, or only failed ones, e.g.), but basically, at the end of your file, you'll want something like this:
var intervalId = window.setInterval( function() {
var elem = document.getElementById("thumb");
// set the source twice, since I dont' see anywhere in the spec if setting
// the src to itself forces a reload.
var src = elem.src;
elem.src = "http://foofoofoofoofoo.bar.bar";
elem.src = src;
}, 300000); // set to every 5 minutes (300 seconds * 1000 milliseconds)
Somewhere in there, you'll need to keep track of how many are still pending, and when it hits 0, call window.clearInterval(intervalId);.

execute code AFTER Recaptcha.reload() is finished

I have a function below which is called to reload a recaptcha image. It works, reloads the image but won't do anything after that. Basically the form is small that has this recaptcha on it so I've shrunk it and allowed for clicking to enlarge and all that. If the person presses "get another captcha" which calls reloadCAP() it checks to see if it has the class of being the larger image. if it does i need it to add that class and css back to the elements AFTER the new image has loaded but I can't seem to get it to work. Any ideas?
function reloadCAP() {
if($("#recaptcha_widget img").hasClass('largecap')) {
Recaptcha.reload();
$("#recaptcha_widget img").addClass('largecap');
$('#recaptcha_image').css('height', '62px');
} else {
Recaptcha.reload();
}
}
here's the html for this:
<div id="recaptcha_widget" class="formRow" style="display:none;">
<span class="f_label">Enter Words Below:</span>
<input type="text" class="setWidth" id="recaptcha_response_field" name="recaptcha_response_field" />
<div class="cantread">
<strong>Can't read this?</strong><br />
Get another CAPTCHA
</div>
<div id="recaptcha_image"></div> <!-- image loaded into this div -->
<div class="clear"></div>
<span class="smalltext">(click to enlarge)</span>
<br clear="all" />
</div>
<script type="text/javascript" src="http://api.recaptcha.net/challenge?k=6LfzMMwSAAAAADV6D04jDE6fKwrJ57dXwOEW-vY3&lang=en"></script>
$("#recaptcha_widget img").one('load',function(){
$("#recaptcha_widget img").addClass('largecap');
$('#recaptcha_image').css('height', '62px');
});
This will put a one time only listener on the load event of the image that you are reloading and then executes the folowing code.
I used .one() instead of .load() here because you don't want to attach a new listener every time you call reloadCAP()
Edit
Ok, so here's what I believe the issue is. When you call Recaptcha.reload() it is removing the <img /> and replacing it with a new one. So when we are trying to attach the event it is getting removed as the image gets removed.
What you need to do is place the class largecap on the recaptcha_image div and modify your css style to look like
.largecap img {
height: whatever;
width: whatever;
}
Not the ideal solution, but you could put the addClass code above Recaptcha.reload() and just delay it by a second or two.
Hope that helps.
It sounds like what you actually need is custom theming such that you can style the captcha/image/etc exactly as needed: https://developers.google.com/recaptcha/docs/customization
If you do want to stick to your current implementation, you can hook into Recaptcha's built in (and undocumented) callback functions prior to calling Recaptcha.create().
//Called after Recaptcha.reload() is finished loading
Recaptcha._alias_finish_reload = Recaptcha.finish_reload;
Recaptcha.finish_reload = function (challenge, b, c) {
//Call original function that creates the new img
Recaptcha._alias_finish_reload(challenge, b, c);
$("#recaptcha_widget img").toggleClass('largecap', true);
}
//Called when the initial challenge is received on page load
Recaptcha._alias_challenge_callback = Recaptcha.challenge_callback;
Recaptcha.challenge_callback= function () {
//Call original function that creates the new img
Recaptcha._alias_challenge_callback();
$("#recaptcha_widget img").toggleClass('largecap', true);
}
The reason you're even having this problem is because Recaptcha destroys and creates a new img everytime it reloads, so the styling you added manually will be lost.

webcam image refresh with ajax

I have an image that is being constantly updated from a local webcam source, it is then displayed on a website. I can get the image to show and by refreshing the page the image will update (obviously).
What I am wondering is, how can I update this image every (lets say) 5 seconds, without having to refresh the page manually (ie. utilizing ajax).
Basic things I am not too sure about:
<img src=""/> <--- how can I load an image url that is located within the javascript code
within the javascript code, how can I create a function that will automatically update the image source, without having to reload the page
As I understand it, upon reading around, one of the main problems is that browsers will load the cached image unless the resulting httprequest looks different each time, as such am I required to add an additional item within the url string (ie. www.yoursire.com?image=foo&date=bar (the date is grabbed by date function or some other iterated value)) in order to circumvent this horrible browser predisposition?
Thanks in advance!
Without writing all the code
look at the javascript functions setTimeout() and setInterval()
it's easy to change the src attribute of ana element
document.getElementbyId("imageId").setAttribute("src", imageUrl);
if your image request url is the same everytime (but the pic has changed server-side) you can either add a "no-cache" to the ajax request header, or possibly add a random query string to the image to force a reload each time (e.g http://mydomain/myimage?3754854 )
With jQuery:
$(document).ready(function() {
window.setInterval("refreshCamera();", 1000); // one second interval
});
var url = 'http://www.x.com/abc?refresh=';
var forcerefresh = 0;
function refreshCamera()
{
forcerefresh = forcerefresh + 1;
$('#myImageId').attr('src',url + forcerefresh);
}
(the force refresh thing is to prevent browser from using locally cached image)
I have done this and it works using setting the image source. Also on the server-side, you have to send no-cache HTTP headers to prevent caching.
<img src="" id="webcam" />
<script type="text/javascript">
var int=self.setInterval("reload()",1000);
function reload(){
$("#webcam").attr("src", "/mysite/webcamImage");
}
</script>
You could use jquery to load an image object and then attach a timer and run the code for every 5 seconds.
Here's an example:
// when the DOM is ready
$(function () {
var img = new Image();
// wrap our new image in jQuery, then:
$(img)
// once the image has loaded, execute this code
.load(function () {
// set the image hidden by default
$(this).hide();
// with the holding div #loader, apply:
$('#loader')
// remove the loading class (so no background spinner),
.removeClass('loading')
// then insert our image
.append(this);
// fade our image in to create a nice effect
$(this).fadeIn();
})
// if there was an error loading the image, react accordingly
.error(function () {
// notify the user that the image could not be loaded
})
// *finally*, set the src attribute of the new image to our image
.attr('src', 'images/headshot.jpg');
});
Read more about this here:
http://jqueryfordesigners.com/image-loading/
About preventing the caching of dynamically loaded images you can just add the last modified timestamp in the url:
<img src="image.jpg?lastmodified=1291235678" ...
I had the same need, so I'm appending my own js solution below. Occasionally our webcam will be in the middle of writing the jpg to a directory when the ajax refresh occurs, so instead of displaying a broken image, I'm presenting an animated gif.
JS:
<script>
$(document).ready(function () {
(function () {
// show webcam jpg on initial page load
var refreshWebcam = function () {
// webcam link is appended with a timestamp to prevent caching
var webcamImg = 'http://abs_path_to_webcam_img/webcam1.jpg' + '?' + (new Date()).getTime();
var loadingImg = 'http://abs_path_to_webcam_loading_img.gif'
$.ajax({
url: webcamImg,
type: 'HEAD',
error: function () {
$('#refresh').attr('src', loadingImg);
//console.log('failed loading ' + webcamImg);
// if there's an error, retry loading image every half second
setTimeout(function () {
refreshWebcam();
}, 500)
},
success: function () {
$('#refresh').attr('src', webcamImg);
//console.log('successfully loaded ' + webcamImg);
}
});
};
// refresh webcam jpg every 5 seconds
window.setInterval(refreshWebcam, 5000);
refreshWebcam();
})();
});
HTML
<img alt="Web Camera Image" id="refresh" src="http://abs_path_to_webcam_loading_img.gif" />
Disabling caching will overwhelm your webcam (even good ones) if it gets popular
I tried allowing the image to be allowed to be cached for 6 seconds (Cache-Control: max-age=6), because I needed to prevent a webcam from being overwhelmed. The code that I was working with looked a bit like this, but it has a problem:
<img alt="Webcam image of something popular" id="liveimage" src="http://example.com/webcams/suddenlypopular.jpg" /><br />
<script type="text/javascript">
(function() {
setInterval(function() {
var myImageElement = document.getElementById('liveimage');
myImageElement.src = 'http://example.com/webcams/suddenlypopular.jpg';
}, 6000);
}());
</script>
Previously, the web-developer had put a ?rand=(random-number) in as a cache-busting technique. That's bad when the image is cacheble (even if only for a short period of time), because if means that you may (depending on whether your cache will consider query parameters as non-cachable), mean you get a very poor cache hit rate and you get a lot of page representations being built up.
The problem was that the image was now not refreshing, because although the src attribute was being reassigned, it wasn't actually changing to a different value, so the browser (Chrome 51) wasn't updating the image. I changed the logic to have either an ?1 or a ?2 query string argument, and alternate between them.
<img alt="Webcam image of something popular" id="liveimage" src="http://example.com/webcams/suddenlypopular.jpg?1" /><br />
<script type="text/javascript">
(function() {
setInterval(function() {
var myImageElement = document.getElementById('liveimage');
if (myImageElement.src == 'http://example.com/webcams/suddenlypopular.jpg?1') {
myImageElement.src = 'http://example.com/webcams/suddenlypopular.jpg?2';
} else {
myImageElement.src = 'http://example.com/webcams/suddenlypopular.jpg?1';
}
myLogElement.innerHTML = myImageElement.src;
}, 6000);
}());
</script>
EDIT: While this works in Chrome and IE, it didn't work in Firefox, so I came up with an alternative solution that is working in Chrome, Firefox and IE (Safari is currently untested).
<img alt="Webcam image of something popular" id="liveimage" src="http://example.com/webcams/suddenlypopular.jpg" />
<script type="text/javascript">
(function() {
setInterval(function() {
var myImageElement = document.getElementById('liveimage');
var d = new Date();
// 6000 is 6 seconds; the desired refresh rate
// % n is a bit of an experiment for being nice on cache invalidation; it also puts a bound on how out-of-date something would be regarding clock skew.
var timeSlice = Math.floor(d.getTime() / 6000) % 3;
myImageElement.src = 'http://example.com/webcams/suddenlypopular.jpg?t=' + timeSlice;
}, 6000);
}());
</script>
So now I have a cache-friendly webcam that does update.
Apache reverse-proxy configuration
Here's a snippet from Apache httpd for how you might reverse-proxy a webcam to set a particular caching policy.
<Location /webcams/suddenlypopular.jpg>
ProxyPass http://mywebcamdevice.example.com/snapshot.jpg
ProxyPassReverse http://mywebcamdevice.example.com/snapshot.jpg
ExpiresByType image/jpeg "access plus 6 seconds"
Header unset ETag
Header unset Last-Modified
</Location>

Categories