Pause JavaScript Code Execution: Top 3 Methods With Examples

While programming in JavaScript we might face scenarios where we need to pause the execution of our program for a while or introduce some delays. Pausing execution will make sure that certain operations are completed and can also help manage the sequence of operations performed. In this article, we’ll look at some ways in which we can introduce delays in our program along with examples.

Methods for Delaying Program Execution

There are several ways in which we can introduce delays into our program. Some of these methods are as follows:

  • Using setTimeout() and setInterval()
  • Using Promises with setTimeout()
  • Using async/await with setTimeout()

1. Using setTimeout() and setInterval()

setTimeout() Function

The setTimeout() is used to delay the execution of the code for a specified period of time.

This function takes two parameters, a function to be executed and the time in milliseconds. Its syntax is as follows:

setTimeout(function, milliseconds);

Example:

Let us take the example of a function showHello() that displays a div element containing ‘Hello’ every 3 seconds.

index.html

<!DOCTYPE html>
<html>
<head>
</head>
<body>
  <script src="index.js"></script>
</body>
</html>

index.js

function showHello() {
    const body = document.querySelector('body')

    const div = document.createElement('div')
    div.innerText = 'Hello'
    body.appendChild(div)

    setTimeout(showHello, 3000);
}

showHello();

Here, in the file index.js containing the JavaScript code, we have written a function showHello(). This creates a div element using the createElement() function and stores it in a constant named div. Then we assign it a text ‘Hello’ using innerText.

We use querySelector to select the body tag from the HTML file and append the div element we created to the body using the appendChild() function.

Finally, we use setTimeout() to call the showHello() function every 3 seconds (3000 milliseconds).

Output:

setTimeout() function displaying ‘Hello’ every 3 seconds

setInterval() Function

setInterlval() works similarly to setTimeout(), except that rather than delaying the execution of a function for a period of time, it calls the function repeatedly at regular intervals.

Like setTimeout(), this function also takes two parameters, a function to be executed and the interval at which it should be executed, in milliseconds. Its syntax is as follows:

setInterval(function, milliseconds);

Example:

Let us take a function showTime() which displays the time on the console at an interval of two seconds.

function showTime() {

    const dateTime= new Date();
    const time = dateTime.toLocaleTimeString();
    console.log(time)
}

setInterval(showTime, 2000);

In this example, we have a function showTime() inside which a new Date object is created using the new Date(). The toLocaleTimeString() method is called on the Date object to retrieve only the time part of the user’s local date and time. The time is displayed on the console using console.log().

Finally, setInterval() is used to call the showTime() function every 2 seconds.

Output:

setInterval() logging the time after every two seconds

2. Using Promises with setTimeout()

If we ever encounter a situation where we have to resolve or reject a promise after a certain delay we can use setTimeout() inside a promise.

Example:

Let us take a function createDelay() which resolves a promise after a delay using setTimeout().

function createDelay(milliseconds) {
    return new Promise(resolve => setTimeout(resolve, milliseconds));
  }
  
  console.log('Displayed before delay');
  
  createDelay(3000)
    .then(() => console.log('Displayed after 3 seconds of delay'));

Inside the createDelay() function we create a new Promise() constructor inside which the resolve function is passed, which will resolve the promise. setTimeout() is used to introduce a delay only after which the promise will be resolved.

The message ‘Display before delay’ is then displayed. createDelay() then creates a delay of 3 seconds and then() is chained to the promise returned by createDelay(). The message ‘Displayed after 3 seconds of delay’ is displayed when the promise is resolved after 3 seconds.

Output:

setTimeout() used within a Promise to cause a delay

3. Using async/await with setTimeout()

The async/await are powerful tools in JavaScript that help us handle asynchronous operations and the good news is it can be used with setTimeout() to easily create delays in our program!

Example:

Let us take the previous example once again but introduce the asynchronous function showDelay() which displays the messages before and after the delay.

function createDelay(milliseconds) {
    return new Promise(resolve => {
      setTimeout(resolve, milliseconds);
    });
  }
  
  async function showDelay() {
    console.log('Displayed before delay');
    await createDelay(3000);
    console.log('Displayed after 3 seconds of delay');
  }
  
  showDelay();

In this example, we have the same function from the previous example, createDelay() in which a new Promise() constructor is created. The resolve function resolves the promise after a delay passed into the createDelay() function as an argument. setTimeout() is used to create a delay after which the promise is resolved.

Then we define an async function showDelay() which first displays the message ‘Displayed before delay’. Here, await is used to wait until the promise is resolved in the createDelay() function. After the promise is resolved the message ‘Displayed after 3 seconds of delay’ is displayed.

Output:

async/await used with setTimeout() to cause a delay

Conclusion

Pausing the execution of code can be a vital part of time-based program execution. It can help us control the sequence of execution of certain operations or cause delays for successful completion of program completion. By understanding setTimeout() and setInterval() and how they can be used with promises and async/await we can unlock the full potential of time control in JavaScript.

Read More: How to Check If a Date Is Today in JavaScript

Reference

https://stackoverflow.com/questions/14249506/how-can-i-wait-in-node-js-javascript-l-need-to-pause-for-a-period-of-time

Nandana Pradosh
Nandana Pradosh
Articles: 27