How to reload img every 5 second using javascript ?
<img src=screen.jpg alt= />
How to reload img every 5 second using javascript ?
<img src=screen.jpg alt= />
Every time you want to reload the image, you must change the image url like so: screen.jpg?rand=123456789 where 123456789 is a randomly generated number, which is regenerated every time you want to reload the image. The browser will think that it is a different image, and actually download it again, instead of retrieve it from the cache. The web server will most likely ignore and discard everything after the question mark.
To cause the reload in the first place, your would have to use Javascript to get the image element and change the source. The easiest option I can see is to give the image element an id
attribute, like so:
<img src=screen.jpg id=myImage />
Then you may change the source of the image:
var myImageElement = document.getElementById('myImage');
myImageElement.src = 'screen.jpg?rand=' + Math.random();
To do this on a set timer, then use the top-level Javascript function setInterval
:
setInterval(function() {
var myImageElement = document.getElementById('myImage');
myImageElement.src = 'screen.jpg?rand=' + Math.random();
}, 5000);
The second argument specifies 5000 milliseconds, which equates to 5 seconds.