Trusted answers to developer questions
Trusted Answers to Developer Questions

Related Tags

node.js

What is setTimeout() in Node.js?

Amaaz Ahmad

Grokking Modern System Design Interview for Engineers & Managers

Ace your System Design Interview and take your career to the next level. Learn to handle the design of applications like Netflix, Quora, Facebook, Uber, and many more in a 45-min interview. Learn the RESHADED framework for architecting web-scale applications by determining requirements, constraints, and assumptions before diving into a step-by-step design process.

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.

RELATED TAGS

node.js

Grokking Modern System Design Interview for Engineers & Managers

Ace your System Design Interview and take your career to the next level. Learn to handle the design of applications like Netflix, Quora, Facebook, Uber, and many more in a 45-min interview. Learn the RESHADED framework for architecting web-scale applications by determining requirements, constraints, and assumptions before diving into a step-by-step design process.

Keep Exploring