A timeout in JavaScript is a useful tool to asynchronously delay the execution of the function. It requires 2 arguments: the function that you’d like to set for the async execution, and the delay after which the function will be called.
If you’re new to the timeouts in JavaScript, I suggest starting with reading these tutorials:
- JavaScript setTimeout, how to delay the function execution
-
How does
setTimeout
work inside thefor
loop?
Cancel setTimout
with clearTimeout
To cancel the scheduled timeout, you should use the function clearTimeout
.
The most important thing to remember is that you need a reference to the timeout you’ve set, so that the JavaScript engine knows what to cancel.
Luckily, that’s what’s returned by the function setTimeout
.
const timeout = setTimeout(() => console.log('Hello world!'), 1000);
console.log(timeout);
This code logs to the console the timeout
object and then the string Hello world!
after a delay of one second.
Let’s see what the timeout
object looks like:
Timeout {
_idleTimeout: 1000,
_idlePrev: [TimersList],
_idleNext: [TimersList],
_idleStart: 83,
_onTimeout: [Function],
_timerArgs: undefined,
_repeat: null,
_destroyed: false,
[Symbol(refed)]: true,
[Symbol(kHasPrimitive)]: false,
[Symbol(asyncId)]: 3,
[Symbol(triggerId)]: 1
}
Now, that you know what’s inside, you can add the function clearTimeout
to cancel the timeout.
const timeout = setTimeout(() => console.log('Hello world!'), 1000);
clearTimeout(timeout);
In this case, nothing will be printed to the screen as you’ve cancelled the scheduled execution with clearTimeout
.