Search code examples
javascriptjoomla2.5webcamsetinterval

javascript crashes browsers


here's my situation : I have written a small javascript code to autorefresh images coming into my server from external source every 5 Seconds, on the same lines as we would refresh images for a webcam.This js needs to be used in website being made using Joomla. problem The Javascript causes the broswers' FF and Chrome to crash after sometime. I'm attaching the code. Please tell me where I'm going wrong.

    <body>
    <center>
     <h2>human cam</h2>
      <img id="pic" src="images/CB1.jpeg" border="0" width="500" height="500" /></center>
      <script language="javascript" type = "text/javascript">

      function refresh() 
     {         

     document.images["pic"].src = "images/CB1.jpeg" + "?" + new Date().getTime();

     setInterval(function(){refresh()}, 5000 );

     }
     window.onload=function(){
 refresh();
    }
    </script>
   </body>

//P.S moderators I've added joomla and webcam as tags because I have picked up the code from people who used it for webcam refresh, so would like their inputs; and Joomla as I need to further integrate this code Thanks


Solution

  • On each call of refresh() you're creating a new timer which calls refresh() which creates a new timer which calls refresh() which creates a new timer...

    Change it to

    function refresh()
        document.images["pic"].src = "images/CB1.jpeg" + "?" + new Date().getTime();
    }
    
    window.onload = function() {
        setInterval(refresh, 5000);
    }