
The JavaScript setInterval() method is a method from the DOM Window object that allows you to run a specific function at a defined interval.
For example, the following fnLog() function will be executed every 1 second:
let timer = setInterval(fnLog, 1000);
function fnLog() {
console.log("Function fnLog executed");
}
The setInterval() method requires two parameters:
- The
functionto execute - The
numberinterval, specifying how often you want to execute the function. Thenumberinterval is in milliseconds, so1000equals to1second.
The setInterval() method also accepts extra parameters that will be passed to the function that you will execute:
setInterval(fnLog, 1000, param1, param2, ...);
For example, the “Hello World” parameter will be passed to the fnLog() function:
// pass "Hello World" to fnLog
let timer = setInterval(fnLog, 1000, "Hello World");
function fnLog(str) {
console.log(str); //"Hello World"
}
The setInterval() method will return an id that you can use to stop the intervals from executing repeatedly.
To stop the intervals, use the clearInterval() method:
clearInterval(timer);
Both the browser and Node.js has the setInterval() method implemented, so you can use the method on both environments.