Technical skill practice
JavaScript Sleep: Await a Delay Without Blocking the Thread
A JavaScript “sleep” can mean waiting for a Promise backed by a timer. Await that Promise inside an async function. Calling setTimeout by itself schedules later work and returns before that work runs.
The task
Collect an ordering trace around a short delay. The assertions check which events happen first, not that the machine wakes at an exact millisecond. The timer is bounded and the process exits after completion.
Runnable Node 22 example
const assert = require('node:assert/strict');
const sleep = ms => new Promise(resolve => setTimeout(resolve, ms));
const trace = [];
async function run() {
trace.push('before');
await sleep(5);
trace.push('after');
}
const pending = run();
trace.push('caller continues');
assert.deepEqual(trace, ['before', 'caller continues']);
pending.then(() => {
assert.deepEqual(trace, ['before', 'caller continues', 'after']);
console.log(trace.join(' -> '));
}).catch(error => { console.error(error); process.exitCode = 1; });
Expected output and explanation
run begins synchronously and reaches its await. The caller can append its own trace entry while the timer is pending. After the delay resolves, execution resumes in run and appends the final entry. Await pauses this async continuation; it does not freeze all JavaScript activity.
An empty busy loop waiting for the clock would behave differently: it occupies the thread and prevents other scheduled callbacks from progressing. This example uses a timer-backed Promise so the waiting work yields instead.
Output from the example
before -> caller continues -> after
Pitfall to check
Node timers do not promise execution at an exact time. Other work can delay the continuation, so use the delay as scheduling intent rather than a precision stopwatch. Ensure a rejected async task reaches a handler, as this script does.
Questions, answered
Will code after sleep(5) wait if I omit await?
No. The function returns a Promise immediately. Await it or otherwise coordinate with its completion when subsequent work depends on the delay.
Sources and examples
ResumizeAI team. Examples are fictional teaching material, not customer results. Replace sample details with your own facts.
Your experience. A complete resume.
Build in Resumize with ATS-friendly templates, guided editing and a live preview. Start free, then upgrade when you need more.
Free account required. Free-plan PDF exports include a watermark.