DEV Community

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

Posted on • Edited on

34 4

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.

Sentry image

Hands-on debugging session: instrument, monitor, and fix

Join Lazar for a hands-on session where you’ll build it, break it, debug it, and fix it. You’ll set up Sentry, track errors, use Session Replay and Tracing, and leverage some good ol’ AI to find and fix issues fast.

RSVP here →

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?

Image of Docusign

🛠️ Bring your solution into Docusign. Reach over 1.6M customers.

Docusign is now extensible. Overcome challenges with disconnected products and inaccessible data by bringing your solutions into Docusign and publishing to 1.6M customers in the App Center.

Learn more