To tell setInterval to only fire x amount of times with JavaScript, we can keep track of the number of times the setInterval
callback is called.
Then when the limit is reached, we can call clearInterval
to stop the setInterval
timer.
For instance, we can write:
let x = 0;
const intervalID = setInterval(() => {
if (++x === 5) {
window.clearInterval(intervalID);
}
console.log('hello')
}, 200);
to keep track of the number of times the setInterval
callback is called with x
.
Then we call setInterval
with a callback that increments x
with ++
in front to return the value of x
after incrementing by 1.
Next, we check if x
is 5 to top the timer with clearInterval
when the setInterval
callback has been called 5 times.
clearInterval
is called with the intervalID
to stop the timer.
And then we call console log to log some message.
200 is the number of milliseconds between each setInterval
call.
As a result, the setInterval
callback will be called 5 times only.