AI Hints
Home›JavaScript Tutorial›Async Practice
JavaScript · Lesson 88 of 138

Practice: Async Countdown

Putting it together.

⏱ 2 min read▶ Video at 1:45:55🎓 Free
Watch this lesson in the JavaScript courseWatch on YouTube ↗Full JavaScript course

Let's put async code together in a small program. A countdown that waits between numbers, then downloads three things at the same time, with a timeout in case one is too slow.

Practice: Async Countdown
From the video: Practice: Async Countdown
  • A small async program
  • A countdown
  • Downloads with a timeout

Sleep and countdown

Sleep is a tiny helper that returns a promise, resolved after some milliseconds. With it, a countdown is just a normal for loop, with await sleep inside. Each number waits before the next. Run it.

app.mjsjavascript
const sleep = (ms) => new Promise(r => setTimeout(r, ms));

async function countdown(from) {
  for (let i = from; i > 0; i--) {
    console.log(i + "...");
    await sleep(200);
  }
  console.log("Go!");
}

await countdown(3);
Output
3...
2...
1...
Go!

A timeout with race

Download pretends to fetch a file, taking a given time. With timeout races a job against a timer that rejects. Whichever settles first wins. The fast files finish, but the slow one loses the race, and we get an error. All settled collects every outcome. Run it.

app.mjsjavascript
const sleep = (ms) => new Promise(r => setTimeout(r, ms));
const download = async (name, ms) => { await sleep(ms); return name; };

function withTimeout(promise, ms) {
  const timer = sleep(ms).then(() => { throw new Error("Timed out"); });
  return Promise.race([promise, timer]);
}

const results = await Promise.allSettled([
  withTimeout(download("a.png", 100), 300),
  withTimeout(download("b.png", 200), 300),
  withTimeout(download("c.png", 900), 300),
]);
for (const r of results) console.log(r.status, r.value ?? r.reason.message);
Output
fulfilled a.png
fulfilled b.png
rejected Timed out

Summary

A sleep helper makes delays easy, race adds timeouts, and all settled collects every result. Next, how JavaScript actually runs async code, the event loop.

Key takeaways
  • sleep helper
  • Promise.race timeout
  • Promise.allSettled
Next up: The Event Loop — how async really works