How Node.js setTimeout works [Practical Examples]

Introduction

The Node.js setTimeout function is built in the Node.js function that runs the specified program after a certain period of time passes. This time is always defined in milliseconds. setTimeout() accepts a callback function as the first argument and the delay time as the second. If the delay argument is omitted, it defaults to 0.

In Node.js, the setTimeout function can be imported from the timers module.

Advertisement

 

Syntax of Node.js setTimeout

1. Without Arguments

This is the most basic way of writing setTimeout function. You only need to pass in the callback function and delay time as arguments to the setTimeout functions.

// Define the callback function
function callbackFunction () {
   // Code here
}
setTimeout(callbackFunction, delayTimeInMS)

 

2. With Optional Arguments

For callback functions that make use of arguments, you can pass in these arguments as parameters to the setTimeout function. 

// Define the callback function
function callbackFunction (arg) {
  // Code here
}
setTimeout(callbackFunction, delayTimeInMS, “passArgHere”)

 

3. Using async/await

This functionality is only available in Node.js version 15 and above. Defining the setTimeout function using the await keyword makes it behave as though it was synchronous. The next line of code will execute after the delay time is up.

const { setTimeout } = require('timers/promises')
function wait {
  await setTimeout(delayTimeInMS)
  console.log(“delayed by time specified”)
}
NOTE:

When writing the setTimeout(), only pass the reference to the function. For instance, the following code is wrong because it executes the function instead.

setTimeout(callbackFunction(), delayTimeInMS, “passArgHere”)

 

How Node.js setTimeout works

setTimeout is a non-blocking function which means that it does not block other functions in the call stack from executing. This means that the delay time specified is not a guarantee. In other words, the delay time is simply the minimum amount of time your function has to wait before it is executed. Since it is a non-blocking function, the blocking functions in the event loop will execute first before setTimeout.

 

Advertisement

Different Examples using Node.Js setTimeout

Example-1: Print “Hello world” after 3 seconds

In the code below, we start by defining a function,  greet, that prints “Hello world” in the console. Next, we will pass in greet function and the time delay of 3000 milliseconds to setTimeout(). Here, the greet function should only be executed after 3 seconds.

function greet() {
  console.log(“Hello world”)
}
setTimeout(greet, 3000)
console.log(“Print first”)

Expected output:

Print first
Hello world

Due to the asynchronous nature of setTimeout(), the ”Print first” statement will be displayed first.

 

Example-2: Using an Argument

We can modify the above example to be dynamic such that it prints a name passed to it. The code will now look like this:

function greet(name) {
  console.log(`Hello ${name}`)
}
// pass argument
setTimeout(greet, 3000, “Jane”)
console.log(“Print first”)

 

Example-3: Using Multiple Arguments

The setTimeout function allows you to pass in as many parameters as you need. The following code has a function that prints a greeting using both the first name and last name. To execute the function after 3 seconds, you should pass it to setTimeout together with the required parameters like below. The arguments passed must be in the same sequence they appear in the callback function.

function greet(name) {
  console.log(`Hello ${firstName} ${lastNamr}`)
}
// pass argument
setTimeout(greet, 3000, “Jane”, “Doe”)
console.log(“Print first”)

Expected output:

Advertisement
Print first
Hello Jane Doe

Note that the statements defined inside the setTimeout function are non-blocking. Consider the following example, the print statements inside setTimeout will run sequentially.

setTimeout(function () {
 console.log(1)
 console.log(2)
 console.log(3)
}, 3000)
console.log(“Print first”)

Expected Output:

Print first
1
2
3

 

Example-4: Using async//await

In node v15 and higher, you can use async/await in your setTimeout functions by importing it from the timers/promises modules. The keyword is used to define a function that resolves a promise. When used with await, the asynchronous setTimeout function behaves like a synchronous one.

const { setTimeout} = require("timers/promises")
const express = require("express")
const app = express()
async function wait() {
  await setTimeout(3000)
  console.log("Run after 3 seconds")
}
wait()
app.listen(3000)

The code above is an example showing how async/await can be used on the setTimeout function. The first step is importing setTimeout from the timers/promises module. You can then define your delay function using the async keyword. In this function, use the await keyword to force the setTimeout function to complete before moving to the next line in the code. If you run the above code, you will notice that “Run after 3 seconds" is printed on the console after approximately 3 seconds.

 

Using Multiple Node.js setTimeout Functions

Consider the following code that uses multiple setTimeout functions.

setTimeout(function () {
 console.log(1)
}, 1000)
setTimeout(function () {
 console.log(2)
}, 1000)
setTimeout(function () {
 console.log(3)
}, 1000)

Looking at it, you would expect that 1, 2, and 3 be printed on the console one after the other but this may not be the case. The program can output the numbers in any order this is because even though JavaScript is single-threaded timers are unpredictable. They can be affected by CPU load, tasks, or other events. To solve this problem, you can either nest your setTimeout functions or use async/await.

 

Advertisement

Example-1: Nesting Multiple setTimeout Functions

In the code below, the next delayed statement is set to run after the current delayed statement has been executed. Even if you vary the delayed times, the code will execute in order it appears every time.

setTimeout(function () {
 console.log(1)
 setTimeout(function () {
   console.log(2)
 }, 1000)
 setTimeout(function () {
   console.log(3)
 }, 1000)
}, 1000)

Expected output:

1
2
3

 

Example-2: Using async//await

While nested functions work, they can become messy and difficult to read and maintain. Using async/await on the other hand simplifies the code making it more understandable.

async function wait () {
 await setTimeout(1000)
 console.log(1)
 await setTimeout(1000)
 console.log(2)
 await setTimeout(1000)
 console.log(3)
}
wait()

Expected output:

1
2
3

Remember to import the setTimeout function from the timers/promises module otherwise it won't work.

 

Clearing setTimeout

setTimeout functions return a timer object that references it. Passing the timer object to the clearTimeout function cancels setTimeout. If you run the code below, the timer will be cleared and the message displayed immediately. Clearing timer objects prevents the triggering of the setTimeout function after it has served its  purpose.

const timerObj = setTimeout(() => {
 console.log('Run after 3 seconds')
}, 3000)
clearTimeout(timerObj)

 

Conclusion

The Node.JS setTimeout function is useful for delaying a function or code for a certain amount of time. Since JavaScript is a single-threaded language, the non-blocking nature of setTimeout ensures that other programs can execute while the delay time passes. However, to mimic a synchronous functions, await can be used with the setTimeout function to block other functions from executing before it does.  Some of the use cases of the setTimeout function involve delaying API fetch calls, performing redirects, and displaying messages after a certain time has passed. Depending on the use case, you can either choose to use either the blocking or the non-blocking technique.

Advertisement

 

Learn more

Discover more about timers from the Node.js timers module documentation.
Understand the JavaScript event loop from this talk.

 

Didn't find what you were looking for? Perform a quick search across GoLinuxCloud

If my articles on GoLinuxCloud has helped you, kindly consider buying me a coffee as a token of appreciation.

Buy GoLinuxCloud a Coffee

For any other feedbacks or questions you can either use the comments section or contact me form.

Thank You for your support!!

Leave a Comment

X