Open In App

How to pause in Node.js for a specific time ?

Last Updated : 07 Oct, 2021
Improve
Improve
Like Article
Like
Save
Share
Report

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:


Like Article
Suggest improvement
Previous
Next
Share your thoughts in the comments

Similar Reads