Repeating with setInterval
setTimeout() runs a function once. setInterval() runs it again and again, each time after the given number of milliseconds, until you stop this interval. It also returns an id, and clearInterval() stops the interval. Here's a rocket's countdown:
const countdown = document.querySelector("#countdown");
let seconds = 3;
countdown.textContent = seconds;
const timer = setInterval(function () {
seconds--;
if (seconds === 0) {
clearInterval(timer);
countdown.textContent = "Liftoff!";
} else {
countdown.textContent = seconds;
}
}, 1000);The page shows 3, a second later 2, then 1, and then Liftoff! At that point, clearInterval(timer) stops the interval, and its function doesn't run any more.
Notice that:
- The function first runs after the first second, not straight away. That's why the script shows the 3 itself, before it starts the interval.
- The variable
secondsis outside the function, so that it remembers the number from one run of the function to the next, like the click counter. Withlet seconds = 3;inside the function, each run would start from 3 again, and the page would show 2 forever. - The interval can stop itself: its function may use
timer, because it runs only later, whentimeralready holds the id.
Typical mistakes:
- Forgetting
clearInterval(): the countdown goes on to 0, -1, -2… for as long as the page is open. clearInterval(seconds): it needs the interval's id, not the number you're counting.- Starting an interval twice, for example with two clicks on a Start button: then two intervals run at once, and the countdown goes twice as fast. As with the rocket in the previous exercise, first stop the previous one with
clearInterval(timer).
Instructions
In the handler of startButton, below its two lines, start an interval that runs every second: it decreases secondsLeft by 1 and shows it in display. Try it: from 3, the timer counts 3, 2, 1, 0, -1… It doesn't stop yet.
Stop it at zero. Next to secondsLeft, create a variable timer with let, and save the interval in it. When secondsLeft gets to 0, stop the interval with clearInterval(timer) and show Time's up! instead of the 0.
When stopButton is clicked, stop the timer with clearInterval(timer). The display keeps the number it shows, so you can see how much time was left.