Definition:
It is used to cancel a timer set with setTimeout() so that the code does not run.
If you change your mind, you can stop it using clearTimeout().
It works like an alarm where you set a time, and if you no longer need it to ring afterward, you turn off the switch.
Now you will clearly understand with the help of the flowchart.
Start
|
v
Write your code inside setTimeout()
|
v
Set the time delay
|
v
Decide: Do you want the code to run?
|
|-- Yes --> Run the setTimeout function
| |
| v
| Wait for the given time
| |
| v
| Code executes
| |
| v
| End
|
|-- No --> Use clearTimeout() to cancel the timer
|
v
Timer is cancelled
|
v
End
Syntax:
let timer = setTimeout(function() {
// This code will run after some time.
}, time_in_milliseconds);
clearTimeout(timer); // It stops the timer before it runs
Example:
// It set a timer to show a message after 3 seconds
let timer = setTimeout(function() {
console.log("This message will not show!");
}, 3000);
// It cancel the timer before it runs
clearTimeout(timer);
console.log("Timer cancelled, message will not appear.");
Output:
Timer cancelled, message will not appear.
