Tuesday, June 4, 2024
 Popular · Latest · Hot · Upcoming
53
rated 0 times [  59] [ 6]  / answers: 1 / hits: 40238  / 14 Years ago, fri, december 31, 2010, 12:00:00

How to reload img every 5 second using javascript ?



<img src=screen.jpg alt= />

More From » javascript

 Answers
4

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.


[#94422] Wednesday, December 29, 2010, 14 Years  [reply] [flag answer]
Only authorized users can answer the question. Please sign in first, or register a free account.
sylviakaitlinj

Total Points: 564
Total Questions: 114
Total Answers: 105

Location: Jordan
Member since Thu, Aug 11, 2022
2 Years ago
sylviakaitlinj questions
;