Codiqo

Learn JavaScript · lesson 20 of 60 · about 9 minutes

Project: Countdown

Sam's page counts down to the next live stream: check the minutes from the schedule, count down with two-digit labels, and finish with Go live!

What you'll learn

  • Count down with a for loop
  • Pad numbers with padStart()
  • Check input and handle the edges

Sam goes live

Sam codes live on stream, and the page should count down to the next one: Live in: 03 02 01 Go live!. The minutes come from Sam's schedule as text, and sometimes there's no stream, or a typo, or a wait of an hour.

The plan

1. Convert the text, and say "No stream planned" unless it's a whole number of at least 1
2. Count down to 1, adding each number with two digits
3. For a long wait, show only the last 10, with "..." in front
4. Finish with Go live!

Two-digit labels

String(n).padStart(2, "0") adds zeros at the front until the text is 2 characters long, so 3 becomes 03 and 10 stays 10. Number.isInteger(n) is true only for a whole number, so 2.5, NaN and text are all caught at once.

The countdown

const start = 10;
for (let i = start; i >= 1; i--) {
  const label = String(i).padStart(2, "0");
  const note = i === start / 2 ? " (halfway!)" : "";
  console.log(`T-${label}${note}`);
}
console.log("🚀 Lift-off!");

Output

T-10
T-09
T-08
T-07
T-06
T-05 (halfway!)
T-04
T-03
T-02
T-01
🚀 Lift-off!

The countdown on Sam's page

const streamText = "3";
const streamMinutes = Number(streamText);
const streamBox = document.querySelector("#stream");
if (!Number.isInteger(streamMinutes) || streamMinutes < 1) {
  streamBox.textContent = "No stream planned";
} else {
  let countdown = streamMinutes > 10 ? " ..." : "";
  for (let i = Math.min(streamMinutes, 10); i >= 1; i--) {
    countdown += ` ${String(i).padStart(2, "0")}`;
  }
  streamBox.textContent = `Live in:${countdown} Go live!`;
}

Tip

Test the edges: 1, 10 and 11 minutes, then 0, 2.5 and a word.

Now try it yourself

This lesson is free in Codiqo, with 10 questions on what you just read. You can only learn to code by writing code, so it ends with a short program you write yourself, which we run and check straight away.