One Thing After Another
A function marked async can wait several times. Each await waits for its Promise, and only then does the function go on to the next line. That makes it easy to describe things that happen one after another, as in a recipe.
For the waiting itself, there's a handy short function, which you'll find in this exercise's script.js:
function wait(ms) {
return new Promise(function (resolve) {
setTimeout(resolve, ms);
});
}It returns a Promise that gets its value once ms milliseconds have passed: setTimeout() calls resolve for it. So await wait(1000); pauses an async function for a second. Compare the rocket's countdown with setInterval() to this one:
launchButton.addEventListener("click", async function () {
for (let seconds = 3; seconds > 0; seconds--) {
countdown.textContent = seconds;
await wait(1000);
}
countdown.textContent = "Liftoff!";
});The loop shows 3 and waits a second, shows 2 and waits, shows 1 and waits, and then the rocket lifts off. There's no interval to stop: the loop simply ends.
Without await, you'd have to put each next step into the function of a timer, inside the function of the previous timer, and the code would grow sideways with every step.
A typical mistake is to forget await before wait(1000): then nothing waits, and all the steps happen at once. You see only the last one.
In the next lesson, you'll wait twice in a row like this: first for a server's answer, then for the data in it.
Instructions
When pressButton is clicked, show an orange Wait… with showLight("Wait…", "orange"), wait a second, and then show a green Walk. Remember to write async before the handler's function.
The green light lasts only a second too: after another second, show a red Don't walk again.
Click the button again while the light is changing, and the steps get mixed up: two handlers are now running at once. Disable pressButton at the start of the handler and enable it again at the end, after the light has turned red.