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:
- 4 Ways to Convert Object into Query String in Node.js
- How to resize images using Node.js
- Node.js: Get domain, hostname, and protocol from a URL
- Top 4 best Node.js Open Source Headless CMS
- 6 best Node.js frameworks to build backend APIs
You can also check out our Node.js category page or PHP category page for the latest tutorials and examples.