DEV Community

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

Posted on • Edited on

12 2

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!

Heroku

Build apps, not infrastructure.

Dealing with servers, hardware, and infrastructure can take up your valuable time. Discover the benefits of Heroku, the PaaS of choice for developers since 2007.

Visit Site

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!

AWS Q Developer image

Your AI Code Assistant

Implement features, document your code, or refactor your projects.
Built to handle large projects, Amazon Q Developer works alongside you from idea to production code.

Get started free in your IDE

👋 Kindness is contagious

Please leave a ❤️ or a friendly comment on this post if you found it helpful!

Okay