You’ve learned “run when clicked.” But triggers aren’t only human actions—time can be a trigger too. “Show a message after 3 seconds,” “count a number down once every second”—let’s learn how to use the two timers.
Once, after ~ seconds: setTimeout
setTimeout(function () {
console.log("3 seconds are up!");
}, 3000);When you run it, the message appears in the console after waiting 3 seconds. The unit of time is milliseconds (one-thousandth of a second).
| How you write it | Meaning |
|---|---|
1000 | 1 second |
500 | 0.5 seconds |
3000 | 3 seconds |
Repeat every ~ seconds: setInterval
setInterval repeats the same thing at a fixed interval. Showing a clock or auto-advancing a slideshow is this timer’s job.
setInterval(function () {
console.log("Called once every second");
}, 1000);Stop the repeat: clearInterval
If you leave setInterval alone, it repeats forever. To stop it, store the timer in a variable and pass it to clearInterval.
const timer = setInterval(function () {
console.log("Still running");
}, 1000);
clearInterval(timer); // ← this stops itThink of it as “keep the timer’s ticket in timer, and when you want it to stop, show the ticket.”
Cancel a reservation: clearTimeout
As it happens, setTimeout has a matching way to stop it too. After you’ve reserved “do this in 3 seconds,” if you change your mind you can cancel it with clearTimeout.
const timer = setTimeout(function () {
console.log("3 seconds are up!");
}, 3000);
clearTimeout(timer); // ← you can cancel it as long as it hasn't run yetThe mechanism is the same ticket system as clearInterval. set reserves, clear cancels with the ticket—learning them as two pairs makes it easier to keep straight.
Let’s see it in action
Combining timers, variables, and if statements, you can build a countdown.
rest by 1 and show it, and when it hits 0 we stop the repeat with clearInterval. “Decrease, check, stop”—all tools you’ve already learned.Summary of this lesson
setTimeout(thing to do, milliseconds)runs it once after ~ milliseconds;setIntervalruns it over and over every ~ milliseconds- The unit is milliseconds. 1 second = 1000 (three zeros)
- Stop a repeat with
clearInterval(the timer's variable)