Sometimes, we want to call a function periodically in JavaScript.
In this article, we’ll look at how to call a function periodically in JavaScript.
How to call a function periodically in JavaScript?
To call a function periodically in JavaScript, we call the setInterval
function.
For instance, we write
const intervalId = setInterval(() => {
console.log("Interval reached every 5s");
}, 5000);
to call setInterval
with a callback that runs every 5 seconds.
We specify the period with the 2nd argument in milliseconds.
setInterval
returns the ID number of the timer.
And we can use clearInterval
with the timer ID number to stop the timer.
Conclusion
To call a function periodically in JavaScript, we call the setInterval
function.