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.
function sleep(ms) {
// returns a Promise<void> that resolves after `ms` milliseconds
}
// 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
});
sleep(0) must not block. It still returns a Promise that resolves on a later turn of the event loop.undefined. Nothing useful is passed in.setTimeout — no busy-loops, no Date.now() polling. Spin-waiting freezes the browser tab.ms — setTimeout itself treats negative values as 0. You don't need to add extra validation; lean on the platform.AbortSignal. Once you call sleep, the timer runs to completion.