These are the notes for JavaScript Coding Questions, episode 21, interview and placement practice for people who finished the SyntaxPilot JavaScript course. Last episode we wrote our own map, filter and reduce. Today we start promise questions with three small functions every real app needs: sleep(ms), retry(fn, times) and timeout(promise, ms) with Promise.race. On the way: why a busy-wait loop freezes everything, why return fn() inside try never retries, and the timer that keeps your program alive after the race is over.
Each question follows the same steps: read the problem, think out loud, the obvious attempt, a real failure, why, the fix, every test case, and the complexity.
Every program was run with Node.js 24 (node main.js), the SyntaxPilot compiler's JavaScript command, and every output below is real. Programs with timers print times rounded to 100 ms, so the numbers are stable from run to run. Programs that use top-level await (await outside any function) work because Node 24 sees the await and runs the file as an ES module.
First: a promise in one minute
- A Promise is a box for a value that will arrive later.
- It starts pending, then becomes fulfilled (with
resolve(value)) or rejected (withreject(error)). Fulfilled or rejected = settled. await ppauses the current async function untilpsettles, then gives its value (or throws its error). The rest of the program keeps running meanwhile.awaiton something that isn't a promise doesn't wait.
const p = new Promise((resolve) => setTimeout(() => resolve("chai ready"), 100));
console.log("ordered");
console.log(await p);
console.log(await 42);
ordered
chai ready
42
Q1: Write sleep(ms)
Problem. await sleep(1000) pauses an async function for one second, without blocking anything else. It should also work with .then().
Real life: making chai. Boil the water, wait, add the tea leaves. Real apps sleep between retries, in animations, and when polling a server.
Attempt 1: just call setTimeout
const t0 = Date.now();
const ms = () => Math.round((Date.now() - t0) / 100) * 100;
function sleep(wait) {
setTimeout(() => {}, wait);
}
async function makeChai() {
console.log("boil water at", ms());
await sleep(1000);
console.log("add tea leaves at", ms());
}
makeChai();
boil water at 0
add tea leaves at 0
sleep returns undefined, not a promise, so await continues at once. The timer runs, but nobody waits for it.
Attempt 2: busy waiting
const t0 = Date.now();
const ms = () => Math.round((Date.now() - t0) / 100) * 100;
function sleep(wait) {
const start = Date.now();
while (Date.now() - start < wait) {}
}
setTimeout(() => console.log("doorbell answered at", ms()), 200);
console.log("boil water at", ms());
sleep(1000);
console.log("add tea leaves at", ms());
boil water at 0
add tea leaves at 1000
doorbell answered at 1000
It waits, but the doorbell (due at 200 ms) is answered at 1000 ms. JavaScript runs your code on one thread: while the while loop spins, nothing else can run (no timers, no clicks, no network replies). This is busy waiting, and it freezes the whole program. Real life: staring at the pot while the doorbell rings.
Fix: a promise that a timer resolves
const t0 = Date.now();
const ms = () => Math.round((Date.now() - t0) / 100) * 100;
const sleep = (wait) => new Promise((resolve) => setTimeout(resolve, wait));
async function makeChai() {
console.log("boil water at", ms());
await sleep(1000);
console.log("add tea leaves at", ms());
await sleep(500);
console.log("pour at", ms());
}
setTimeout(() => console.log("doorbell answered at", ms()), 200);
makeChai();
sleep(300).then(() => console.log("then() works too at", ms()));
boil water at 0
doorbell answered at 200
then() works too at 300
add tea leaves at 1000
pour at 1500
The event loop (JavaScript's loop that runs whatever is ready next) stays free while we wait, so the doorbell is on time. When the timer fires, it calls resolve, and makeChai continues where it stopped. Real life: set a kitchen timer and walk away.
Complexity: O(1) time and space: one timer; waiting costs nothing because the thread is free.
Q2: Write retry(fn, times)
Problem. retry(fn, times) calls the async function fn. If it rejects, it tries again, up to times tries in total, and returns the first success. If every try fails, it rejects with the last error. Wait between tries.
Real life: a UPI payment fails because the network blinked. Trying again usually works.
A fake payment for testing: flakyPay(n) makes a function that fails the first n times, then succeeds.
Attempt: return fn() inside try
function flakyPay(failTimes) {
let calls = 0;
return async (amount) => {
calls++;
if (calls <= failTimes) throw new Error(`network down (try ${calls})`);
return `paid Rs ${amount} on try ${calls}`;
};
}
async function retry(fn, times) {
for (let i = 1; i <= times; i++) {
try {
return fn();
} catch (err) {
console.log("retrying after:", err.message);
}
}
}
const pay = flakyPay(2);
retry(() => pay(250), 3)
.then(console.log)
.catch((err) => console.log("failed:", err.message));
failed: network down (try 1)
It never retried. fn is async, so it doesn't throw: it returns a promise that rejects. return fn() hands that promise back at once and leaves the function; when it rejects, the try block is gone, so catch never runs. The caller gets the first rejection.
Fix: return await, keep the last error, back off
function flakyPay(failTimes) {
let calls = 0;
return async (amount) => {
calls++;
if (calls <= failTimes) throw new Error(`network down (try ${calls})`);
return `paid Rs ${amount} on try ${calls}`;
};
}
const sleep = (ms) => new Promise((r) => setTimeout(r, ms));
async function retry(fn, times, wait = 100) {
let lastError;
for (let i = 1; i <= times; i++) {
try {
return await fn();
} catch (err) {
lastError = err;
console.log(`try ${i} failed: ${err.message}`);
if (i < times) await sleep(wait * 2 ** (i - 1));
}
}
throw lastError;
}
const pay = flakyPay(2);
console.log(await retry(() => pay(250), 3));
const deadPay = flakyPay(5);
try {
await retry(() => deadPay(99), 2);
} catch (err) {
console.log("gave up:", err.message);
}
try 1 failed: network down (try 1)
try 2 failed: network down (try 2)
paid Rs 250 on try 3
try 1 failed: network down (try 1)
try 2 failed: network down (try 2)
gave up: network down (try 2)
return await fn(): the rejection now happens inside thetry, socatchsees it.- Exponential backoff: the wait doubles each time (100 ms, 200 ms, 400 ms…), so a struggling server gets more room.
2 ** kis 2 to the power k. throw lastErrorafter the last try, so the caller knows why it failed (without it, the caller would getundefined).- We pass
() => pay(250), a function, notpay(250): retry needs to start a new call each time. A promise can't be restarted.
Complexity: up to n calls of fn, so O(n) times the cost of one call, plus the waits; O(1) extra space.
Q3: Write timeout(promise, ms)
Problem. timeout(promise, ms) settles like promise if it settles within ms; otherwise it rejects with Error: timed out after ms ms. Use Promise.race([a, b]), which settles like whichever settles first.
Real life: a food delivery app asks where the rider is. If the answer takes more than a second, show the map anyway.
The problem: a slow call
const t0 = Date.now();
const ms = () => Math.round((Date.now() - t0) / 100) * 100;
process.on("exit", () => console.log("program ended at", ms()));
const sleep = (wait) => new Promise((r) => setTimeout(r, wait));
async function trackRider(delay) {
await sleep(delay);
return `rider is 2 km away (${delay} ms)`;
}
console.log(await trackRider(3000));
console.log("map shown at", ms());
rider is 2 km away (3000 ms)
map shown at 3000
program ended at 3000
process.on("exit", fn) runs fn just before Node exits, so we can see when the program really ends. The user stared at a spinner for 3 seconds.
Attempt: Promise.race with a timer
const t0 = Date.now();
const ms = () => Math.round((Date.now() - t0) / 100) * 100;
process.on("exit", () => console.log("program ended at", ms()));
const sleep = (wait) => new Promise((r) => setTimeout(r, wait));
async function trackRider(delay) {
await sleep(delay);
return `rider is 2 km away (${delay} ms)`;
}
function timeout(promise, limit) {
const timer = new Promise((_, reject) =>
setTimeout(() => reject(new Error(`timed out after ${limit} ms`)), limit));
return Promise.race([promise, timer]);
}
console.log(await timeout(trackRider(200), 5000), "at", ms());
try {
await timeout(trackRider(3000), 1000);
} catch (err) {
console.log(err.message, "at", ms());
}
rider is 2 km away (200 ms) at 200
timed out after 1000 ms at 1200
program ended at 5000
Both answers are right, but the program ended at 5000: the first call's 5-second timer lost the race and was never cancelled. It kept ticking and kept the program alive. On a server, every fast request would leave one of these timers behind.
Fix: clear the timer in finally
const t0 = Date.now();
const ms = () => Math.round((Date.now() - t0) / 100) * 100;
process.on("exit", () => console.log("program ended at", ms()));
const sleep = (wait) => new Promise((r) => setTimeout(r, wait));
async function trackRider(delay) {
await sleep(delay);
return `rider is 2 km away (${delay} ms)`;
}
function timeout(promise, limit) {
let id;
const timer = new Promise((_, reject) => {
id = setTimeout(() => reject(new Error(`timed out after ${limit} ms`)), limit);
});
return Promise.race([promise, timer]).finally(() => clearTimeout(id));
}
console.log(await timeout(trackRider(200), 5000), "at", ms());
try {
await timeout(trackRider(700), 500);
} catch (err) {
console.log(err.message, "at", ms());
}
console.log(await timeout(Promise.resolve("cached"), 500));
rider is 2 km away (200 ms) at 200
timed out after 500 ms at 700
cached
program ended at 900
.finally(fn)runsfnwhen the promise settles, either way, and passes the result or error through unchanged.- The program ends at 900, not 700: the slow rider (started at 200, takes 700 ms) still finishes.
Promise.racedoesn't cancel the loser, it just stops listening. To really stop the work, use anAbortController(below).
Complexity: O(1): one extra promise and one timer, cleared as soon as the race is decided.
Going further: really cancel the slow work with AbortController
An AbortController makes a signal you pass to the work; calling controller.abort() tells the work to stop. fetch and many Node APIs accept a signal. AbortSignal.timeout(ms) makes a signal that aborts by itself.
const t0 = Date.now();
const ms = () => Math.round((Date.now() - t0) / 100) * 100;
process.on("exit", () => console.log("program ended at", ms()));
function trackRider(delay, signal) {
return new Promise((resolve, reject) => {
const id = setTimeout(() => resolve(`rider is 2 km away (${delay} ms)`), delay);
signal.addEventListener("abort", () => {
clearTimeout(id);
reject(new Error("tracking cancelled"));
});
});
}
try {
console.log(await trackRider(3000, AbortSignal.timeout(500)));
} catch (err) {
console.log(err.message, "at", ms());
}
tracking cancelled at 500
program ended at 500
Now the slow work itself stops, so the program ends at 500.
Complexity summary
| Function | Time | Extra space |
|---|---|---|
sleep(ms) |
O(1) work (the wait is free) | O(1) |
retry(fn, n) |
up to n calls of fn + backoff waits |
O(1) |
timeout(p, ms) |
O(1) | O(1): one timer |
Common mistakes (and the exact outputs)
| Mistake | Code | What you see | Why | Fix |
|---|---|---|---|---|
sleep returns nothing |
setTimeout(() => {}, wait) |
boil water at 0, add tea leaves at 0 |
await undefined doesn't wait |
return new Promise((r) => setTimeout(r, wait)) |
| Busy waiting | while (Date.now() - start < wait) {} |
doorbell answered at 1000 |
one thread, the loop blocks it | a timer + resolve |
return fn() in try |
try { return fn(); } catch {} |
failed: network down (try 1) |
the rejection happens after we left the try |
return await fn() |
No final throw |
a retry loop that only logs | resolves undefined |
nothing thrown after the last try | throw lastError |
Passing a promise to retry |
retry(pay(250), 3) |
TypeError: fn is not a function |
a promise can't be restarted | retry(() => pay(250), 3) |
| Race without cleanup | Promise.race([p, timer]) |
program ended at 5000 |
the losing timer keeps ticking | .finally(() => clearTimeout(id)) |
Thinking race cancels |
timeout(slowWork(), 500) |
the slow work still runs | race only stops listening | AbortController |
The retry(pay(250), 3) row, for real:
async function pay(amount) { return `paid Rs ${amount}`; }
async function retry(fn, times) {
for (let i = 1; i <= times; i++) {
try { return await fn(); } catch (err) { if (i === times) throw err; }
}
}
retry(pay(250), 3).catch((err) => console.log(err.constructor.name + ":", err.message));
TypeError: fn is not a function
Mini project: a resilient order tracker
retry + timeout + sleep together: each try gets a 300 ms limit, and the tracker retries up to 3 times.
const t0 = Date.now();
const ms = () => Math.round((Date.now() - t0) / 100) * 100;
const sleep = (wait) => new Promise((r) => setTimeout(r, wait));
function timeout(promise, limit) {
let id;
const timer = new Promise((_, reject) => {
id = setTimeout(() => reject(new Error(`timed out after ${limit} ms`)), limit);
});
return Promise.race([promise, timer]).finally(() => clearTimeout(id));
}
async function retry(fn, times, wait = 100) {
let lastError;
for (let i = 1; i <= times; i++) {
try {
return await fn();
} catch (err) {
lastError = err;
console.log(` try ${i} at ${ms()}: ${err.message}`);
if (i < times) await sleep(wait * 2 ** (i - 1));
}
}
throw lastError;
}
const delays = [800, 600, 200];
let call = 0;
const fetchStatus = async () => {
const d = delays[call++] ?? 100;
await sleep(d);
return `order #42: out for delivery (${d} ms)`;
};
console.log(await retry(() => timeout(fetchStatus(), 300), 3), "at", ms());
try 1 at 300: timed out after 300 ms
try 2 at 700: timed out after 300 ms
order #42: out for delivery (200 ms) at 1100
Try 1 starts at 0 and times out at 300; wait 100 → try 2 starts at 400, times out at 700; wait 200 → try 3 starts at 900 and succeeds after 200 ms, at 1100. Each try's timeout clears its own timer, so nothing is left running.
Your turn: retry only some errors (solution)
Problem. A wrong UPI PIN should never be retried (three wrong PINs can block the account), but a network error should. Add an option shouldRetry(err).
const sleep = (ms) => new Promise((r) => setTimeout(r, ms));
async function retry(fn, times, { wait = 100, shouldRetry = () => true } = {}) {
let lastError;
for (let i = 1; i <= times; i++) {
try {
return await fn();
} catch (err) {
if (!shouldRetry(err)) throw err;
lastError = err;
console.log(`try ${i} failed: ${err.message}`);
if (i < times) await sleep(wait * 2 ** (i - 1));
}
}
throw lastError;
}
function payWith(errors) {
let call = 0;
return async () => {
const code = errors[call++];
if (code) throw Object.assign(new Error(code.toLowerCase()), { code });
return `paid on call ${call}`;
};
}
const onlyNetwork = { shouldRetry: (err) => err.code === "NETWORK" };
console.log(await retry(payWith(["NETWORK", "NETWORK"]), 3, onlyNetwork));
try {
await retry(payWith(["NETWORK", "WRONG_PIN"]), 3, onlyNetwork);
} catch (err) {
console.log("stopped:", err.code);
}
try 1 failed: network
try 2 failed: network
paid on call 3
try 1 failed: network
stopped: WRONG_PIN
Object.assign(error, { code }) adds a code property to the error. The third argument uses destructuring with defaults, so retry(fn, 3) still works with no options.
Practice questions (with solutions)
1. retry with a maximum total time. Stop retrying once maxMs have passed since the first try.
Solution
const sleep = (ms) => new Promise((r) => setTimeout(r, ms));
async function retryFor(fn, maxMs, wait = 100) {
const start = Date.now();
let lastError;
for (let i = 1; ; i++) {
try {
return await fn();
} catch (err) {
lastError = err;
const next = wait * 2 ** (i - 1);
if (Date.now() - start + next > maxMs) break;
await sleep(next);
}
}
throw new Error(`gave up after ${maxMs} ms: ${lastError.message}`);
}
let calls = 0;
const alwaysDown = async () => { calls++; throw new Error("network down"); };
try {
await retryFor(alwaysDown, 1000);
} catch (err) {
console.log(err.message, "| calls:", calls);
}
gave up after 1000 ms: network down | calls: 4
Waits of 100, 200 and 400 ms fit in one second (700 ms); the next wait, 800 ms, would not.
2. poll(fn, every, until): call fn every every ms until until(result) is true.
Solution
const sleep = (ms) => new Promise((r) => setTimeout(r, ms));
async function poll(fn, every, until, maxTries = 10) {
for (let i = 1; i <= maxTries; i++) {
const result = await fn();
console.log(`check ${i}: ${result}`);
if (until(result)) return result;
await sleep(every);
}
throw new Error("still not done");
}
const steps = ["placed", "cooking", "cooking", "picked up", "delivered"];
let n = 0;
const status = async () => steps[Math.min(n++, steps.length - 1)];
await poll(status, 100, (s) => s === "picked up");
check 1: placed
check 2: cooking
check 3: cooking
check 4: picked up
3. Predict the order.
const sleep = (ms, v) => new Promise((r) => setTimeout(() => r(v), ms));
sleep(200, "B").then(console.log);
sleep(0, "A").then(console.log);
await sleep(100);
console.log("C");
console.log(await Promise.race([sleep(50, "D"), "E"]));
Answer
A
C
E
B
A at 0 ms, C at 100 ms. Promise.race treats the plain value "E" as an already-resolved promise, so it wins at once. B arrives at 200 ms (and D is ignored).
4. sleep that can be cancelled with an AbortSignal.
Solution
function sleep(ms, signal) {
return new Promise((resolve, reject) => {
const id = setTimeout(resolve, ms);
signal?.addEventListener("abort", () => {
clearTimeout(id);
reject(new Error("sleep cancelled"));
});
});
}
const controller = new AbortController();
setTimeout(() => controller.abort(), 100);
const t0 = Date.now();
try {
await sleep(5000, controller.signal);
} catch (err) {
console.log(err.message, "after about", Math.round((Date.now() - t0) / 100) * 100, "ms");
}
sleep cancelled after about 100 ms
?. (optional chaining) skips the call when no signal is given.
5. Why is this retry wrong?
async function retry(fn, times) {
for (let i = 0; i < times; i++) {
fn().catch(() => console.log("failed, retrying"));
}
}
Answer
There's no await, so all times calls start at once (in parallel), not one after another; the function returns undefined before any of them finishes; a success doesn't stop the others; and errors are swallowed, so the caller never learns the result. Use return await fn() inside try in a loop, as in Q2.
Quick quiz
const sleep = (ms, v) => new Promise((r) => setTimeout(() => r(v), ms));
const win = await Promise.race([sleep(300, "bus"), sleep(100, "auto")]);
console.log(win);
console.log(await Promise.race([]));
A) auto, then undefined B) bus, then undefined C) auto, then a warning: unsettled await D) auto, then bus
Answer
C. The auto settles first (100 ms), so the first race gives auto. Promise.race([]) never settles: the await waits forever, nothing else keeps the program alive, so Node exits with Warning: Detected unsettled top-level await (exit code 13), and the second console.log never runs.
Interview questions
- How do you write
sleepin JavaScript?const sleep = (ms) => new Promise((r) => setTimeout(r, ms)); - Why not a
whileloop? JavaScript runs on one thread; a busy loop blocks timers, events and I/O. return fn()vsreturn await fn()insidetry? Onlyreturn awaitlets thecatchsee an async rejection.- What is exponential backoff, and why? Waiting longer after each failure (100, 200, 400 ms…) so an overloaded server can recover; often with random jitter added so clients don't retry together.
- Which errors should you retry? Temporary ones (network, timeouts, HTTP 503). Not permanent ones (wrong PIN, HTTP 400/401/404).
- What does
Promise.racedo with the losing promises? Nothing: they keep running; their results are ignored. - How do you implement a timeout? Race the promise against a timer that rejects; clear the timer in
finally. - What is
AbortController? A way to signal cancellation to work that accepts anAbortSignal(fetch, timers in Node, streams). Promise.racevsPromise.any?racesettles with the first to settle (even a rejection);anyfulfils with the first to fulfil and rejects only if all reject.
Glossary
| Term | Meaning |
|---|---|
| Promise | A box for a value that arrives later |
| Pending / fulfilled / rejected | The three states of a promise |
| Settled | Fulfilled or rejected |
resolve / reject |
Functions that fulfil / reject a new promise |
| Async function | A function marked async; it always returns a promise |
await |
Pause the async function until a promise settles |
Top-level await |
await outside any function; works in ES modules |
| ES module | The standard JavaScript module format (import/export) |
setTimeout(fn, ms) |
Run fn after at least ms milliseconds; returns a timer id |
clearTimeout(id) |
Cancel a timer that hasn't run yet |
| Thread | One line of execution; JavaScript runs your code on one |
| Busy waiting | Looping until time passes; blocks the thread |
| Event loop | The loop that runs whatever is ready next: timers, I/O, promise callbacks |
| Retry | Calling a failed operation again |
| Exponential backoff | Doubling the wait after each failure |
| Jitter | A small random extra wait, so many clients don't retry at the same moment |
Promise.race |
Settles like the first of the promises to settle |
.finally(fn) |
Runs fn on fulfilment or rejection; passes the result through |
| Timeout | Giving up after a time limit |
process.on("exit", fn) |
Run fn just before Node exits |
AbortController / AbortSignal |
An object to cancel work / the signal the work listens to |
| Exit code | A number a program returns when it ends; 0 means success |
| Big-O | How the work grows with the input size |
Summary
awaitonly waits for a promise.sleep=new Promise((r) => setTimeout(r, ms)). Never busy-wait: it blocks the one thread.retryloops withreturn await fn()insidetry, waits longer each time (backoff), and throws the last error at the end. Pass a function, not a promise.timeout=Promise.raceagainst a timer that rejects, withfinallyclearing the timer.racedoesn't cancel the loser;AbortControllerdoes.- Next episode: promise questions II: write your own
Promise.all,Promise.allSettled, and a task runner with a concurrency limit.