Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to reload img every 5 second using javascript?

Tags:

How to reload img every 5 second using javascript ?

<img src="screen.jpg" alt="" /> 
like image 724
faressoft Avatar asked Dec 31 '10 20:12

faressoft


People also ask

How do you refresh a page after 2 seconds?

Use location. reload() method in setTimeout() to reload page after specific seconds using JavaScript.

How do I refresh an image in HTML?

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.

How do I refresh a page after some time?

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.


1 Answers

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.

like image 51
AniDev Avatar answered Oct 18 '22 19:10

AniDev