What is setTimeout
?
setTimeout()
is a function that waits for some time and then runs your code.
Example:
This will print "Hello after 3 seconds!"
after waiting 3000 milliseconds (3 seconds).
How to Cancel setTimeout
?
Sometimes you don’t want that code to run — maybe the user clicked a button or something changed. You can cancel it using clearTimeout()
.
Easy Step-by-Step:
-
When you use
setTimeout()
, it gives you an ID. -
You save that ID in a variable.
-
Use that ID with
clearTimeout()
to stop the timer.
Simple Example:
This will only print:
It will not show "This message will NOT be shown."
because we canceled the timer before it ran.
Real-Life Example: Cancel Auto Save
Imagine your app saves something after 5 seconds — but if the user clicks "Save" earlier, we cancel the auto-save.
Summary (Super Simple):
Function | What it does |
---|---|
setTimeout() | Runs code after waiting some time |
clearTimeout() | Stops that code from running |