How to Pause/Sleep Code Execution in JavaScript

JavaScript is single threaded. This means that it has only one main thread of execution, which processes code sequentially, one instruction at a time. So, it is not a good idea to block the execution because that would mean no other code can run when the thread is blocked. Still, in a lot of use cases you might need pause the execution of JavaScript and wait before executing the next line of code.

While there’s no official method for pausing JavaScript execution, you can accomplish this using a combination of async/await and the setTimeout() method. Here’s a concise one-liner that demonstrates this technique:

const pauseExecution = (ms) => new Promise((res) => setTimeout(res, ms));
await pauseExecution(10000); // pause for 10 seconds

This function can also be written as below

const pauseExecution = async (milliseconds) => {
  await new Promise((resolve) => {
    return setTimeout(resolve, milliseconds);
  });
};

await pauseExecution(10000); // pause for 10 seconds

This defines an async function called pauseExecution that takes the number of miliseconds to pause as an argument. It uses a Promise combined with setTimeout to create a delay, allowing you to introduce a pause in your JavaScript code without blocking the main thread. This is a simple and quite useful method if you need to pause the execution of JavaScript for a few seconds before letting it run.

Leave a Reply

Your email address will not be published. Required fields are marked *