clearTimeout and clearInterval Are Interchangeable!

clearTimeout and clearInterval Are Interchangeable!

Did you know you can use clearTimeout and clearInterval interchangeably? 🤯

  const myIntervalFunc = setInterval(() => {
    console.log('Hello World');
  }, 100);

  clearTimeout(myIntervalFunc); // clearTimeout works!

This is because both functions will return a random ID which gets saved in the browser's memory but there's no separate group of IDs that are allocated to setTimeout versus setInterval; they're shared.

It's easy to forget that the return value of these functions is really a numerical ID. You can check it out if you log the variable:

  const myFunc = setTimeout(() => {}, 0);
  console.log(myFunc); // 1205 (<- This will be random)

And since the parameter to clearTimeout and clearInterval is the ID of the function you wish to cancel, and they're from the same pool of IDs on the window object, both functions will work for either a timeout or interval! 😃

So while you could use these functions interchangeably, I actually wouldn't since you'll probably just confuse others - but it's still cool to know why this works!

Links

MDN Article on setTimeout


Check out more #JSBits at my blog, jsbits-yo.com. Or follow me on Twitter!

Â