| by Arround The Web | No comments

How to Pause Execution in Node.js?

The delay or pause in the execution of code means that the user wants to execute it after a particular time interval. It plays an important role while waiting for the API response and taking the user input before moving on. In addition, it also allows the users to schedule the program execution in a well-organized manner as per requirements.

This guide will exemplify how to pause execution in Node.js.

Pre-requisites: Before moving on to the practical implementation of any method, first create a “.js” file of any name and write all the source code to it. Here, we have created an “index.js” file.

How to Pause Execution in Node.js?

This section lists all possible methods to pause execution in Node.js:

Let’s start with the “setInterval()” method.

Method 1: Pause Execution in Node.js Using “setInterval()”

The pre-defined “setInterval()” method pauses the specified code block execution for a particular time interval and runs it after the given delay for infinite times. It is the scheduling method of the “Timers” module that schedules the program execution as per requirements. It does not stop itself until its associated “clearInterval()” method is invoked.

The following code block pauses the given function execution for the specified delay:

const setTimeID = setInterval(myFunc, 1000);

function myFunc() {

  console.log("Welcome to Linuxhint!")

}

In the above code snippet:

  • The “setTimeID” variable utilizes the “setInterval()” method that specifies the targeted function and a time delay as its first and second arguments respectively. It will execute the given function after the particular delay.
  • Inside the function definition, the “console.log()” method displays the enquoted statement infinite times in the console after the given number of milliseconds.

Output

Initiate the “index.js” file using the “node” keyword:

node index.js

The below output shows that the specified function execution pauses for a particular time delay:

Method 2: Pause Execution in Node.js Using “setTimeout()”

The “Timers” module also offers another scheduling method “setTimeout()” to pause the execution of a specific part of a program. This method pauses the desired code block execution and runs it only once after a specified time delay. Its working can be stopped within the given time interval using the “clearTimeout()” method.

Here is its practical implementation:

const myTimeout = setTimeout(myFunc, 2000);

function myFunc() {

  console.log("Welcome to Linuxhint!")

}

In the above code lines:

  • The “myTimeout” variable utilizes the “setTimeout()” method to run the given function only one time after the specified “delay”.
  • Inside the function, the “console.log()” method shows the quoted text statement in the console.

Output

Execute the “index.js” file:

node index.js

The below out executes the specified function after the particular number of milliseconds(delay):

Method 3: Pause Execution in Node.js Using “async/await”

In node.js, a “promise” is an action that can either be resolved or rejected. It performs long-running operations asynchronously instead of stopping the remaining program execution. It can be easily written or created using the “async” and “await” keywords.

The “async” returns a promise and the “await” keyword is used inside the “asynchronous” function to pause its execution until the promise is resolved.

The below-code block writes a “promise” and applies the “async” and “await” keywords to return a promise and pause the given function execution until the promise is fulfilled:

function delay(time) {

  return new Promise(resolve => setTimeout(resolve, time));

  }

demo();

  async function demo() {

  await delay(2000);

  console.log('Linuxhint');

}

The explanation of the above lines of code is stated here:

  • Firstly, define a function named “delay()” passing the “time” parameter.
  • Inside this function, the “Promise()” constructor creates a new promise taking the “resolve” arrow function as its argument. The “resolve” arrow function further applies the “setTimeout()” method to run the given function after the specified delay when the promise is resolved.
  • Next, call the “demo()” function.
  • After that, the “async” keyword defines the “demo()” function, which will display the “string” specified in the “console.log()” method after the given delay.

Output

Run the “index.js” file:

node app.js

The output shows that the specified function executes after a given delay when the promise is resolved:

Method 4: Pause Execution in Node.js Using “sleep-promise”

Another useful method to pause execution in Node.js asynchronously is the “sleep-promise” package. This is an external package that resolves the promise after the given delay.

Before using the “sleep-promise” package first install it via the “npm(node package manager)”:

npm install sleep-promise

The above command successfully added the “sleep-promise” package inside the current Node.js project:

Now, use the “sleep-promise” package to pause the execution of the specified function:

const sleep = require('sleep-promise');

(async () => {

   console.log("Program started....");

   await sleep(3000);

   console.log("\nLinuxhint! is printed after three seconds.");

})();

In the above code snippet:

  • The “require()” method imports the installed “sleep-promise” package in the project.
  • The “async” keyword defines a void arrow function that first uses the “console.log()” method to display a specified statement. After that, it utilizes the “sleep()” function with the “await” keyword to execute the remaining code block after the given delay.
  • The “()” parenthesis calls the defined empty arrow function.

Output

Execute the “index.js” file:

node index.js

The following illustration shows that the “sleep()” function executes the particular code block after the specified delay:

That’s all about pausing the execution in Node.js.

Conclusion

To pause execution in Node.js, use the built-in “setInterval()”, or “setTimeout()” methods of the “Timers” module. Furthermore, this task can also be performed asynchronously using the “async/await” or “sleep-promise” package. All of these approaches are straightforward to use. The user can implement any of them based on the requirements. This guide has practically explained all possible methods to pause execution in Node.js (JavaScript).

Share Button

Source: linuxhint.com

Leave a Reply