How to reload img every 5 second using javascript ?
<img src="screen.jpg" alt="" />
Use location. reload() method in setTimeout() to reload page after specific seconds using JavaScript.
newImage. src = "http://localhost/image.jpg?" + new Date(). getTime(); This will append the current timestamp automatically when you are creating the image, and it will make the browser look again for the image instead of retrieving the one in the cache.
Auto Refresh You can also use JavaScript to refresh the page automatically after a given time period. Here setTimeout() is a built-in JavaScript function which can be used to execute another function after a given time interval.
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With