Skip to the content

Why waiting exists

JavaScript · Unit 18: Asynchronous code

Some things take time: asking for data, waiting for an answer. JavaScript doesn't stand still meanwhile: it writes down what has to happen later and moves on to the line below.

setTimeout(fn, ms) is exactly that: it saves a function for later.

setTimeout(() => {
  console.log("second");
}, 500);
console.log("first");

Prints

first
second

The rest of the explanation is in the lesson, which is part of the full plan.

Exercises in this lesson

You do them in the app, which checks them on the spot and explains why.

  1. 1. Predict the output

    What does this code print?

  2. 2. Complete the code

    Fill in so it prints "now" first and "ready" after.

  3. 3. Complete the code

    Fill in so it prints C, then B and A last.

  4. 4. Multiple choice

    In setTimeout(remind, 1000), what is the 1000?

  5. 5. Predict the output

    What does this code print?

  6. 6. Find the bug

    It should count 1, 2 and 3 in that order. Which line has the error?

  7. 7. Predict the output

    A countdown. What does it print?

  8. 8. Find the bug

    It should run three rounds, report back and turn itself off. Look at the error you get when it runs. Which line causes it?

  9. 9. Predict the output

    What does this code print?

Do this lesson

It opens in your browser. This lesson is part of the full plan; the first unit of each course is free.

See all lessons →