How do you pause execution for a few seconds in Node.js using async/await? | A1Lab@FahadM to JavaScriptEnglish • 3 days ago

How do you pause execution for a few seconds in Node.js using async/await?

message-square
0

To pause execution for a few seconds in Node.js using async/await, await a Promise that resolves after a setTimeout() delay—either by importing setTimeout from node:timers/promises (recommended in modern Node.js) or wrapping setTimeout(resolve, ms) in a small helper function. Awaiting the delay pauses only the current async function while keeping the Node.js event loop non-blocking for other requests, timers, and I/O.


1. Using node:timers/promises in Modern Node.js

Node.js provides a built-in promise-based setTimeout in node:timers/promises, so you can await delay(ms) directly without writing a manual wrapper:

// Built-in promise-based delay in Node.js (milliseconds)
import { setTimeout as delay } from "node:timers/promises";

async function runWithPause() {
  console.log("Start task");
  await delay(2500); // Pause this async function for 2.5 seconds
  console.log("Resumed after 2.5 seconds");
}

runWithPause();
  • Clean built-in API: node:timers/promises avoids boilerplate new Promise wrappers and supports AbortSignal for cancellation.
  • Non-blocking event loop: await suspends only that async flow; other Node.js operations continue running concurrently.

2. Creating a Custom sleep(ms) Helper Function

If you want a reusable sleep(ms) helper across modules or older codebases, wrap setTimeout(resolve, ms) inside a Promise and validate the delay duration:

// Reusable async sleep helper (validates non-negative finite milliseconds)
function sleep(ms) {
  if (typeof ms !== "number" || !Number.isFinite(ms) || ms < 0) {
    throw new RangeError("Expected delay ms to be a non-negative finite number.");
  }

  return new Promise((resolve) => {
    setTimeout(resolve, ms);
  });
}

async function retryWithBackoff(operation, attempts = 3) {
  for (let i = 1; i <= attempts; i += 1) {
    try {
      return await operation();
    } catch (err) {
      if (i === attempts) throw err;
      await sleep(1000 * i); // Pause 1s, 2s, etc. before retrying
    }
  }
}

// Example usage:
(async () => {
  await sleep(1500);
  console.log("Paused for 1.5 seconds via sleep()");
})();
  • Must use await: Calling sleep(2000) without await starts the timer and moves on immediately instead of pausing.
  • Great for retries and rate limits: Pauses inside loops help space out external API calls or backoff retries cleanly.

3. Cancellable Delays and Avoiding Blocking Calls

When a delay might need to be aborted early—such as on request disconnect or shutdown—pass an AbortController.signal to node:timers/promises and catch AbortError, while avoiding synchronous blocking loops:

// Cancellable pause using AbortController
import { setTimeout as delay } from "node:timers/promises";

async function cancellablePause(signal) {
  try {
    await delay(5000, undefined, { signal });
    console.log("Completed full 5s pause");
  } catch (err) {
    if (err.name === "AbortError") {
      console.log("Pause cancelled early");
      return;
    }
    throw err;
  }
}

const controller = new AbortController();
setTimeout(() => controller.abort(), 1000);
cancellablePause(controller.signal);
  • Avoid busy-wait loops: Never use a while (Date.now() < end) spin loop to pause—it freezes the event loop and pins CPU at 100%.
  • Top-level await requires ESM: Use await at the top level in ES modules (.mjs or "type": "module"), or inside an async function in CommonJS.

TL;DR: Pause execution in Node.js with async/await by awaiting setTimeout(ms) from node:timers/promises or a small new Promise((resolve) => setTimeout(resolve, ms)) helper—keeping the event loop non-blocking and avoiding busy-wait loops.