Trusted answers to developer questions

What is setInterval() in Node.js?

Free System Design Interview Course

Many candidates are rejected or down-leveled due to poor performance in their System Design Interview. Stand out in System Design Interviews and get hired in 2024 with this popular free course.

The setInterval function calls a function repeatedly after a specific number of milliseconds. It is found in the Timers module of Node.js.

Parameters

setInterval(callback,[, delay[, ...args]] )

In the above snippet of code, callback is a function that will be executed repeatedly for an infinite number of times. Each call will be separated by the number of milliseconds specified by delay. Both of these arguments are followed by an optional list of parameters passed onto callback as input parameters.

Return value

The function returns a Timeout object which can be used in other function calls, e.g., clearInterval.

Examples

console.log("Before the setInterval call")
let timerID = setInterval(() => {console.log("2 seconds have passed")}, 2000);
console.log("After the setInterval call")

An arrow function has been passed as a parameter to the setInterval function in the above example.

We can see that the arrow function inside the setInterval function is executed repeatedly after the specified duration until the session is stopped or expires.

function myFunction(platform){
console.log("Hi, Welcome to " + platform);
}
console.log("Before the setInterval call")
let timerID = setInterval(myFunction, 2000, "Educative");
console.log("After the setInterval call")

In the above example, the function named myFunction takes a single argument.

In the setInterval function call, the third parameter acts as an argument for the delayed call to myFunction.

RELATED TAGS

node.js

CONTRIBUTOR

Amaaz Ahmad
Copyright ©2024 Educative, Inc. All rights reserved
Did you find this helpful?