Sometimes, we want to tell setInterval to only fire x amount of times with JavaScript.
In this article, we’ll look at how to tell setInterval to only fire x amount of times with JavaScript.
How to tell setInterval to only fire x amount of times with JavaScript?
To tell setInterval to only fire x amount of times with JavaScript, we call clearInterval
after the setInterval
callback has been called x
times.
For instance, we write
let x = 0;
const intervalID = setInterval(() => {
// ...
if (++x === 5) {
clearInterval(intervalID);
}
}, 1000);
to call setInterval
with a callback that runs every second.
We keep track of the number of times the callback is called with x
.
We increment x
each time the callback is run.
If x
is 5, then we call clearInterval
with the intervalID
to stop running the setInterval
callback after it ran 5 times.
Conclusion
To tell setInterval to only fire x amount of times with JavaScript, we call clearInterval
after the setInterval
callback has been called x
times.