What is setImmediate() in Node.js?

The setImmediate function is used to execute a function right after the current event loop finishes. In simple terms, the function functionToExecute is called after all the statements in the script are executed. It is the same as calling the setTimeout function with zero delays. The setImmediate function can be found in the Timers module of Node.js.

Parameters

 setImmediate(functionToExecute, [, ...args] )

The call to the function named functionToExecute is scheduled by the setImmediate function, and it will be called right after all statements in the script are executed. It is invoked on the “check handles” level of the current event loop.

More detail about the event loop and setImmediate function can be found here.

It is followed by an optional list of parameters passed onto functionToExecute as input parameters.

If the first parameter, i.e.,functionToExecute is not a function, then a TypeError will be thrown

Return value

The function returns a unique timer identifier that can be used in another function call, i.e., clearImmediate.

Examples

console.log("Before the setImmediate call")
let timerID = setImmediate(() => {console.log("Hello, World")});
console.log("After the setImmediate call")

In the above example, the function has been passed as a parameter to the setImmediate function.

We can see that the function inside the setImmediate function is executed after all the statements in script have finished executing.

function myFunction(platform){
console.log("Hi, Welcome to " + platform);
}
console.log("Before the setImmediate call")
let timerID = setImmediate(myFunction, "Educative");
console.log("After the setImmediate call")
for(let i=0; i<10; i++){
console.log("Iteration of loop: "+i);
}

In the above example, an argument is passed to myFunction through the setImmediate function.

The function passed to setImmediate is called after all the statements in the script are executed.

Copyright ©2024 Educative, Inc. All rights reserved