Timeout errors can be frustrating and difficult to debug. In this article, we'll show you how to clear all timeouts in JavaScript. We will provide the appropriate method for doing so.
Creating Timeouts using setTimeout
To create timeouts or wait for a code, we can make use of the setTimeout
method. The setTimeout
method takes two main parameters - code
, delay
- to execute your code after a set time. The code
parameter (a function that could be anonymous) is required, but the delay
parameter is optional (and the default value is 0). We can have other additional parameters which are passed through to the function that we passed.
setTimeout(code, delay, arg1, ..., argN)
We will create a simple setTimeout
code to allow us to showcase how to clear all timeouts.
let timeoutID = setTimeout(
(user) => {
console.log(`${user}, please provide your ID.`);
},
2000,
"Jacob"
);
Output
Jacob, please provide your ID.
Now, how do we cancel or clear all timeouts? By using the clearTimeout
method.
Clear All Timeouts using clearTimeout
To cancel out or clear all timeouts created by the setTimeout
, we need the clearTimeout
method which only takes one parameter - timeoutID
- which is the setTimeout
identifier. In the above section where we created a simple timeout, the setTimeout
identifier is timeoutID
, the binding name.
So, if we want to clear out the timeout from the previous section, we will pass the binding name of the timeout to the clearTimeout
method.
let timeoutID = setTimeout(
(user) => {
console.log(`${user}, please provide your ID.`);
},
2000,
"Jacob"
);
clearTimeout(timeoutID);
Output
Yes, nothing will be outputted because the timeout has been canceled (and therefore, the setTImeout
will not be executed.
Note that if you don’t bind (or attach a variable name) to the setTImeout
, you can’t make use of the clearTimeout
. In addition, if you pass the wrong identifier, you will not get an error, and the timeout will still exist.
Summary
To clear all timeouts in JavaScript, you need the clearTimeout
function and the binding name for the setTimeout
method operation. With this, the code within the setTimeout
method will not run and should be used based on the condition. Also, remember to bind the setTImeout
operations unless you will not be able to clear their timeout operations.
References
clearTimeout() - Web APIs | MDN (mozilla.org)