SleepLoading saved progress…

Sleep

JavaScript has no built-in sleep — you can't pause execution synchronously the way time.sleep(2) works in Python. The async-friendly equivalent is to return a Promise that resolves after a delay, then await it. That's what you're building.

Implement sleep(ms). It takes a number of milliseconds and returns a Promise that resolves (with undefined) after at least ms milliseconds have elapsed. The function itself returns immediately — only the await pauses your code.

Signature

function sleep(ms) {
  // returns a Promise<void> that resolves after `ms` milliseconds
}

Examples

// Basic usage with await
async function demo() {
  console.log('start');
  await sleep(500);
  console.log('half a second later');
}
demo();
// Pure-promise usage (no async/await)
sleep(200).then(() => console.log('done'));

// Resolves with undefined
sleep(50).then((value) => {
  console.log(value); // undefined
});

Notes

  • Asynchronous, always — even sleep(0) must not block. It still returns a Promise that resolves on a later turn of the event loop.
  • Resolve value — the Promise resolves with undefined. Nothing useful is passed in.
  • Use setTimeout — no busy-loops, no Date.now() polling. Spin-waiting freezes the browser tab.
  • Negative or non-numeric mssetTimeout itself treats negative values as 0. You don't need to add extra validation; lean on the platform.
  • No cancellation — this version has no AbortSignal. Once you call sleep, the timer runs to completion.
Loading editor…