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)
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}
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)
With this id
and the clearTimeout
JavaScript function, you can cancel a setTimeout
.
Here's the syntax of the clearTimeout
function:
clearTimeout(timeoutId)
With this, we can have:
const timeoutId = setTimeout(() => {
console.log("hey...I'm 2 seconds in"
}, 2000}
// later on
clearTimeout(timeoutId)
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)
Thanks, this is short and useful!
I'm glad you found it useful :)
Nice
wow
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?