Skip to the solution
EasyFrontend4 min read

Implement sleep(ms) and delay with value

115 views

The problem

Problem, as an interviewer would state it: "Write a sleep(ms) function I can await to pause execution for a given number of milliseconds, and a delay(value, ms) function that resolves with a given value after that delay. Show me you understand what actually makes this 'pause' different from a language like Python's time.sleep()."

Examples:

Code
await sleep(100);           // pauses ~100ms, resolves with undefined
await delay("done", 100);   // pauses ~100ms, resolves with "done"

Clarifying questions expected:

  • Does "pause" mean genuinely blocking everything else on the page, or just pausing the calling async function while other code keeps running? (This is the crux of the whole problem.)
  • Is a rejection path ever needed (a cancellable sleep), or is resolve-only fine for this version?
  • Is sub-millisecond precision expected, or is "close to ms" acceptable? (Real timers are never exact.)

Code / implementation expected: Yes — both functions, plus a real, direct demonstration that the implementation does not block the event loop, since that is the entire point of the question.

  • sleep
  • delay
  • promise

Try it yourself

Sketch your approach before you read the solution. That is what the interview tests.

Stuck? Get a hint.

A short nudge toward the approach. It will not give the answer away.

Solution

The solution is hidden so you can try first

4 min read · 9 sections

Run the code

Edit the code and run it here. Each console line with an expected value becomes a test.

JavaScriptReal, direct proof: setTimeout-based sleep never blocks the event loop, while a busy-wait genuinely does — verified directly

Discussion

Other approaches, follow-ups and how it went in real interviews.

Sign in to join the discussion.

No comments yet. Share how you would answer it.

Question 43 of 154 in JavaScript coding

Keep your momentum going.

Mark this question solved to track your progress, then take the next one while it is fresh.

Up nextEasy

Implement dedupe / unique — remove duplicates preserving order

Continue