Node.js: Executing a Piece of Code after a Delay

Updated: August 26, 2021 By: A Goodman Post a comment

In Node.js, we can use the setTimeout function to run a piece of code after a delay.

You can call setTimeout directly or use it with async/await.

Example 1 – setTimeout

This code runs a function named sayHello after 1000 milliseconds (as close to 1000ms as possible):

const sayHello = (name) => {
  console.log(`Hello ${name}. Welcome to KindaCode.com`);
}

console.log('Waiting...');
setTimeout(sayHello, 1000, 'John Doe');

Output:

Waiting...
Hello John Doe. Welcome to KindaCode.com

Example 2 – setTimeout and async/await

The code:

// Kindacode.com
const delay = (duration) => {
  return new Promise((resolve) => setTimeout(resolve, duration));
};

const mainFunction = async () => {
  console.log("Hello");
  await delay(2000); // Delay 2s
  console.log("Goodbye");
};

mainFunction();

Output:

Hello

// After 2s
Goodbye

Final Words

We’ve gone through a couple of examples of delaying a function in Node.js. Continue exploring more about the awesome Javascript runtime by reading the following articles:

You can also check out our Node.js category page or PHP category page for the latest tutorials and examples.

Subscribe
Notify of
guest
0 Comments
Inline Feedbacks
View all comments

Related Articles