Home
← All questions

Implement sleep: Delay with a JavaScript Promise

EasyFree
Asked at:Freshworks
Was this asked in an interview?

JavaScript interview practice: Return a promise that settles only after the given number of milliseconds so callers can await a timed pause.

Problem

Write a small utility you can await inside an async function to pause execution for a chosen number of milliseconds — useful for spacing out attempts, animations, or polling.

Implement sleep(ms) that returns a promise which resolves after ms milliseconds.

Input

async function run() {
  console.log("start");
  await sleep(1000);
  console.log("one second later");
}
run();

Expected output

  • "start" logs immediately.
  • "one second later" logs ~1000ms afterwards.

Implement:

function sleep(ms) {
  // Your code here
}