HomePremium · ₹1199
← All questions

Wait for N milliseconds using a Promise

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

Implement a promise-based sleep/delay utility you can await.

Problem

There is no built-in sleep in JavaScript, but async/await makes it trivial to build one — handy for spacing out retries, animations, or polling.

Implement sleep(ms) that returns a promise which resolves after ms milliseconds, so you can await sleep(1000) inside an async function.

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
}
Wait for N milliseconds using a Promise — JavaScript Interview Question | Mentoxis