DEV Community

Cover image for How to cancel a setTimeout in JavaScript
Dillion Megida
Dillion Megida

Posted on • Updated on

How to cancel a setTimeout in JavaScript

setTimeout in JavaScript is a native function that sets a function to be executed when a specified timer completes.

Here's the syntax:

setTimeout(function, timer)
Enter fullscreen mode Exit fullscreen mode

timer is in milliseconds. Here's an example where we do something after two seconds:

setTimeout(() => {
  console.log("hey...I'm 2 seconds in")
}, 2000}
Enter fullscreen mode Exit fullscreen mode

Cancelling a setTimeout

You may not want a setTimeout to complete for various reasons. One reason can be cleaning up side-effects in React useEffect. So how do you stop it? Here's how...

The setTimeout function returns an id when declared:

const timeoutId = setTimeout(() => {}, 1000)
Enter fullscreen mode Exit fullscreen mode

With this id and the clearTimeout JavaScript function, you can cancel a setTimeout.

Here's the syntax of the clearTimeout function:

clearTimeout(timeoutId)
Enter fullscreen mode Exit fullscreen mode

With this, we can have:

const timeoutId = setTimeout(() => {
  console.log("hey...I'm 2 seconds in"
}, 2000}

// later on

clearTimeout(timeoutId)
Enter fullscreen mode Exit fullscreen mode

If the setTimeout declaration has not been completed, the clearTimeout function will cancel it, and the callback function will not be executed anymore.

Top comments (5)

Collapse
 
curiousdev profile image
CuriousDev

Thanks, this is short and useful!

Collapse
 
dillionmegida profile image
Dillion Megida

I'm glad you found it useful :)

Collapse
 
leonardofrp5 profile image
Leonaro Romero Perez

Nice

Collapse
 
yomassive profile image
Andrew Belykh

wow

Collapse
 
laurentgth profile image
Laurent

Thanks for this consise summary. In addition to this, would you know whether a setTimeout is discarded automatically by the system when the given duration is reached or still exists after?