What is setTimeout() in Node.js?

widget

The setTimeout function is used to call a function after the specified number of milliseconds. The delay of the called function begins after the remaining statements in the script have finished executing. The setTimeout function is found in the Timers module of Node.js.

Parameters

let timerID = setTimeout(functionToExecute, millisecondsToDelay, [arg1ForFunctionToExecute], [arg2ForFunctionToExecute], ...)

In the above snippet of code, functionToExecute is a function that will be executed after the number of milliseconds specified by millisecondsToDelay. Both of these arguments are 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 other function calls, e.g., clearTimeout.

Examples

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

An arrow function is passed as an argument to the setTimeout function in the above example. The delay is set to be 1000 milliseconds1 second.

We can observe by the output that the execution of the arrow function is delayed by 1 second. However, the overall execution of the program does not stop. Hence, it is an asynchronous function. This is why the output of line 3 appears before “Hello, World” on the console.

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

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

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

Copyright ©2024 Educative, Inc. All rights reserved