Skip to content
Related Articles

Related Articles

Improve Article

How to pause in NodeJS for a specific time ?

  • Last Updated : 18 Feb, 2021

Sometimes we need to execute some function after some amount of time like you asked for something from the user and the details are required for the next function from the server end. That time we will require a pause in our server. So to pause for a specific time we use the setTimeout() function. It has a callback function attached to it which gets executed after a given amount of time. The setTimeout() can be used to execute the code after a given amount of milliseconds.

There is one thing you can do for multiple functions that you can break the functions into different blocks of code and use the setTimeout() between them.

Syntax:

setTimeout(function, milliseconds);

Below example illustrate the approach of pausing the NOdeJS by using setTimeout() function:

Example: This function uses setTimeout() under the hood and shows geek! After Hello after 2 seconds. Here the file name is wait.js.



wait.js




function sleep(ms) {
  return new Promise((resolve) => setTimeout(resolve, ms));
}
  
console.log("Hello");
sleep(2000).then(() => {
  console.log("Geek!");
});

Output:

My Personal Notes arrow_drop_up
Recommended Articles
Page :