Search code examples
javascriptimagereload

How can I reload an image on a time interval?


I have two images that need to be reloaded in x time. I tried to do it this way:

<script>
 function srcreload(){
     imguser=document.getElementsByName("userimage")[0];
     imgme=document.getElementsByName("me")[0];
     imguser.src=imguser.src;imgme.src=imgme.src;setTimeout("srcreload()",15000);};
     setTimeout("srcreload()",15000);
</script>
  <img src="somesrc" name="userimage">
  <img src="someothersrc" name="me">

Why isn't this working and how do I fix it? I got it to work one time, but then I must have changed something because it is no longer working.


Solution

    1. Use var.
    2. Don't pass a string to setTimeout, but a function.
    3. Indent properly.

    If you indent nicely, you see an extraneous }, which doesn't belong there.

    var url = "...";
    
    function srcreload() {
        var imguser = document.getElementsByName("userimage")[0];
        var imgme = document.getElementsByName("me")[0];
    
        var random = "?" + Math.random();
    
        imguser.src = url + random;
        imgme.src = url + random;
    
       setTimeout(srcreload, 15000);
    }
    
    setTimeout(srcreload, 15000);