Stopping a timer in JavaScript
You already know how to start a timer, now let's learn
how to stop it. To do this, you need to know that each
timer started with the setInterval
function has
a unique number. This number is returned by the
setInterval
function when the timer starts:
let timerId = setInterval(function() {
console.log('!')
}, 1000);
alert(timerId); // will display the number of the timer
To stop the timer, use the clearInterval
function,
which takes a unique number of the timer to be stopped.
For example, let's start a timer that prints numbers
to the console in ascending order, starting with 1
.
Let's stop the timer as soon as the number 10
is displayed on the screen:
let i = 0;
let timerId = setInterval(function() {
console.log(++i);
if (i >= 10) {
clearInterval(timerId);
}
}, 1000);
Let a variable be given that initially stores the
number 10
. Start a timer that every second
will decrease the value of this variable by 1
and print this value to the console. As soon as the
value of the variable reaches zero, stop the timer.