Search code examples
javascriptevent-loop

How does reassigning the timeout variable impact Settimeout


Consider This:

var x = null;

function a() {
  x = window.setTimeout(() => {
    alert("hello")
  })
}

a();

function b() {
  window.clearTimeout(x);
  alert("bye")
}

b();

The above snippet would only print bye and not hello. However, if I just reassign x in the method b, both hello and bye would be printed. What's the mechanism?

var x = null;

function a() {
  x = window.setTimeout(() => {
    alert("hello")
  })
}

a();

function b() {
  x = undefined;
  window.clearTimeout(x);
  alert("bye")
}

b();


Solution

  • The "timeout variable" is just a number, the ID of the timeout. Reassigning the variable the number is assigned to isn't a problem in itself, but if you want to clear a timeout, you'll have to pass the same timeout ID to the clearTimeout. Just for illustration, not that you should do this in real code, you can call setTimeout at the beginning of pageload and get a timeout ID of 1, then call clearTimeout with 1, and the timeout will be cleared:

    x = window.setTimeout(() => {
      alert("hello")
    });
    window.clearTimeout(1);

    The variable itself is nothing special, it's just the value, the number, that you need to keep track of so you can pass it to clearTimeout.

    In your second snippet, because you're assigning undefined to x before doing clearTimeout(x), the interpreter doesn't know of an ongoing timeout with an id of undefined, so it doesn't clear anything.

    You could also assign the timeout ID number to a different variable, and clear the original variable:

    var x = null;
    
    function a() {
    
      x = window.setTimeout(() => {
        alert("hello")
      })
    }
    a();
    
    function b() {
      const savedX = x;
      x = undefined;
      window.clearTimeout(savedX);
      alert("bye")
    }
    b();