3 Powerful Ways to Pause JavaScript Execution (With Practical Examples)

Feat 20269 Png

Sometimes JavaScript runs too fast, and things just break. Or worse, you are in an interview and someone asks, “How do you pause JavaScript?” and your mind goes blank. Don’t worry, here are three simple ways to pause JavaScript, with examples that actually make sense.

Key Takeaways

  • setTimeout helps us delay a task for a certain amount of time, so we can control when something happens in our program.
  • setInterval lets us repeat a task at regular time intervals, which is useful for things like animations or checking for updates.
  • Both setTimeout and setInterval work in the background, so our program does not stop while waiting for the timer.
  • We can stop a repeated task by using clearInterval with the identifier returned from setInterval.
  • Using Promises with setTimeout helps us write cleaner code when we want to wait before moving to the next step.
  • Combining async and await with setTimeout makes our code easier to read when we need to pause and wait for something to finish.
  • Timers are not always exact, so the delay might be a little longer if the browser is busy or the tab is not active.

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

Common Pitfalls

Forgetting to clear timers

When we do not use clearTimeout or clearInterval, timers keep running and can cause memory leaks or unwanted actions.

Solution: Always clear timers when they are not needed anymore.

Example: If we use setInterval to update a clock, use clearInterval when the clock is stopped.

Using setInterval for tasks that take time to finish

When a function inside setInterval takes longer than the interval, calls can overlap and cause bugs or slowdowns.

Solution: Use a recursive setTimeout so the next call waits for the previous one to finish.

Example: For repeated data fetches, use setTimeout after each fetch completes.

Setting very short intervals or delays

Very short times in setInterval or setTimeout can overload the browser and make the page slow or unresponsive.

Solution: Use longer intervals and test performance on real devices.

Example: Instead of updating every 10 milliseconds, try every 500 milliseconds and check if it works well.

Using setInterval for one-time actions

Using setInterval when only one delay is needed can cause the action to repeat by mistake.

Solution: Use setTimeout for single delays.

Example: Show a message after 2 seconds with setTimeout instead of setInterval.

Frequently Asked Questions

What does it mean to pause JavaScript execution?

Pausing JavaScript execution means making the program wait for a certain amount of time before continuing, which helps us control when certain actions happen in our code.

Why might we want to delay code execution in JavaScript?

We might want to delay code execution to make sure some operations finish before others start, or to create timed actions like animations or repeated updates.

What is the setTimeout function used for?

The setTimeout function lets us run a piece of code once after a specific delay, which is set in milliseconds.

How does setInterval differ from setTimeout?

setInterval runs a function repeatedly at regular time intervals, while setTimeout only runs the function once after the delay.

Can we stop a setTimeout or setInterval once it starts?

Yes, we can stop setTimeout with clearTimeout and setInterval with clearInterval by using the unique identifier each function returns.

What is the basic syntax for using setTimeout?

The basic syntax is setTimeout(function, milliseconds) where the function is what we want to run and milliseconds is the delay time.

How can we use promises with setTimeout to pause execution?

We can wrap setTimeout inside a promise, which lets us use modern JavaScript features like async and await to pause code execution in a more readable way.

What is an example of using async and await with setTimeout?

We can create a function that returns a promise with setTimeout, then use await to pause the code until the timeout is over, making the code easier to follow.

Are setTimeout and setInterval accurate for timing?

These functions are not perfectly accurate because browser or system tasks can cause delays, so the actual wait time might be a bit longer than what we set.

What happens if we do not stop a setInterval?

If we do not stop a setInterval, it will keep running forever, which can slow down the program or cause performance problems.

Can we use these timing functions in both browsers and Node.js?

Yes, both setTimeout and setInterval work in browsers and Node.js, though they are part of different global objects in each environment.

AI Dev Assistant Tips

AI coding assistants like JetBrains AI Assistant, GitHub Copilot, and Qodo help us write, explain, and refactor JavaScript code. These tools can suggest better ways to pause execution, explain how async and await work, and help us avoid callback issues. They also offer code examples and debugging tips for delays in JavaScript.

Copy-Paste-Ready AI Prompt

Explain three ways to pause JavaScript execution, with simple code examples and when to use each method.

  • Ask for code explanations or step-by-step guides for setTimeout and async functions.
  • Request code reviews to spot mistakes in delay logic.
  • Use AI to compare different delay methods for clarity.

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

About the Author

Aditya Gupta is a Full Stack Developer with over 3 years of experience building scalable and maintainable web applications. He is passionate about writing clean code and helping other developers level up their skills in the modern JavaScript ecosystem.

Connect on LinkedIn: https://www.linkedin.com/in/dev-aditya-gupta/

Review Your Cart
0
Add Coupon Code
Subtotal