About
setInterval permits to execute a function at regulier interval.
If you want to call it once, you can use the setTimeout function
Example
- Increment and log the variable i every 3 seconds. The intervalFunctionId is called a timerId. setTimeout uses the same timeId pool. It is used in the clearInterval function to stop the execution.
let i = 0;
intervalFunctionId = setInterval(()=>{
i++;
if (i<10) {
console.log("Executed after "+i*3 +" seconds");
}
}, 3000) // every 3 seconds
- Stop the interval function with a setTimeout after 9 seconds.
setTimeout(()=>{
window.clearInterval(intervalFunctionId);
console.log("Interval function "+intervalFunctionId +" was cleared");
}, 9000) // after 9 seconds
Management
Clear
clearInterval function gets the return id value of the setInterval function.