Why waiting exists
JavaScript · Unit 18: Asynchronous code
- Full plan
- JavaScript
- 9 exercises
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. Predict the output
What does this code print?
2. Complete the code
Fill in so it prints "now" first and "ready" after.
3. Complete the code
Fill in so it prints C, then B and A last.
4. Multiple choice
In
setTimeout(remind, 1000), what is the 1000?5. Predict the output
What does this code print?
6. Find the bug
It should count 1, 2 and 3 in that order. Which line has the error?
7. Predict the output
A countdown. What does it print?
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. Predict the output
What does this code print?
It opens in your browser. This lesson is part of the full plan; the first unit of each course is free.