Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Auto update Image

I have an image and I want to automatically update it using either javascript, jquery or ajax.

Until now I have the following code.

<html>

<head>
<script language="JavaScript"><!--
  function refreshIt() {
    if (!document.images) return;
      document.images['myCam'].src = 'swt.png';
      setTimeout('refreshIt()',50); // refresh every 50ms
 }
  //--></script>
</head>

<body onLoad=" setTimeout('refreshIt()',50)">

<img src="swt.png" name="myCam">

</body>

</html>

I think it is not working because the browser is caching the image and it is not updating the image correctly.

Can someone provide me a working example?

like image 494
glarkou Avatar asked Dec 10 '11 21:12

glarkou


4 Answers

This will do the trick, but it's a nightmare as far as performance.

<html>
    <head>
        <script language="JavaScript">
            function refreshIt(element) {
                setTimeout(function() {
                    element.src = element.src.split('?')[0] + '?' + new Date().getTime();
                    refreshIt(element);
                }, 50); // refresh every 50ms
            }
        </script>
    </head>
    <body>
        <img src="swt.png" name="myCam" onload="refreshIt(this)">
    </body>
</html>
like image 107
benastan Avatar answered Nov 05 '22 08:11

benastan


Just add a random number to the query string on every refresh. This will trick the browser into thinking this is a different resource, while the server will serve the same picture.

like image 39
Fyodor Soikin Avatar answered Nov 05 '22 10:11

Fyodor Soikin


On top of loading a different image each time and increasing the refresh time, you should start the setTimeout again after the image has fully loaded.

function refreshIt() {
    if (!document.images) return;
      var img = new Image();
      img.src = 'swt.png'; // use a random image

      img.addEventListener('load', function () {
          // you should cache the image element
          document.images['myCam'].src = this.src; 
          setTimeout(refreshIt, 50); // refresh every 50ms    
      }, false);
    }

}
like image 2
Trevor Avatar answered Nov 05 '22 08:11

Trevor


You are setting the image source to the same string. That will not refresh the image, the browser thinks it already has that image, and won't issue another request. Try adding a random query parameter each time you want to refresh - then the browser should see the image as different resources.

like image 1
driis Avatar answered Nov 05 '22 08:11

driis