DEV Community

Cover image for clearTimeout and clearInterval Are Interchangeable!
JS Bits Bill
JS Bits Bill

Posted on • Edited on

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!
Enter fullscreen mode Exit fullscreen mode

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)
Enter fullscreen mode Exit fullscreen mode

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!

Top comments (2)

Collapse
 
bias profile image
Tobias Nickel

definitely, this is a surprise.
in node.js however the return value of setTimeout is not a number but an object.

I also wonder if that is something to rely on. a browser vendor could change that easily, or is this behavior even part of the js spec?,...

very interesting indeed. Thanks for sharing

Collapse
 
js_bits_bill profile image
JS Bits Bill • Edited

@tobiasnickel - that's interesting that it's an object in Node. Great question - I was curious myself and interestingly enough setTimeout/setInterval are actually part of the HTML Standard and not the ECMAScript Language Spec:
html.spec.whatwg.org/multipage/tim...

So it seems that Node has it's own special implementation of these APIs that return a special "Timer" object as you mentioned: nodejs.org/api/timers.html#timers_...

Thanks for sharing that!