Search code examples
javascripttimernullsetinterval

Why do I need "var timer = null;" when I use "timer = setInterval();"?


To make an image spin by mousing over, I wrote like this.

In JavaScript,

var images=["img1.png", "img2.png", "img3.png"];
var i = 0;
var timer = null;
window.onload = function() {
$("startButton").observe("mouseover", startSpin);
}
function startSpin() {
timer = setInterval(changeImage, 100);
}
function changeImage() {
i++;
if (i > 2) {
i = 0;
}
$("img").src = images[i];
}

Why do I need "var timer = null;" as a global variable? I do not understand why the code does not work without this.


Solution

  • Let's take a look at what it would look like without that line:

    var images=["img1.png", "img2.png", "img3.png"];
    var i = 0;
    window.onload = function() {
      $("startButton").observe("mouseover", startSpin);
    }
    function startSpin() {
      timer = setInterval(changeImage, 100);
    }
    function changeImage() {
      i++;
      if (i > 2) {
        i = 0;
      }
      $("img").src = images[i];
    }
    

    Without the initial var timer = null;, the first time timer is mentioned is in the startSpin function. There, it has no idea what timer is, because it's never been defined. You would need the startSpin function to look like this:

    function startSpin() { let timer = setInterval(changeImage, 100); }

    If done this way, you shouldn't need the initial var timer = null;.