Summary
In this lesson, you learned that:
setTimeout(function () { ... }, 2000)runs the function once, 2000 milliseconds (2 seconds) later. Pass the function itself, without().- The script doesn't wait for a timer: the lines after
setTimeout()run straight away, so everything that should happen after the wait goes into the function. setTimeout()returns the timer's id, andclearTimeout(timer)cancels the timer. Keep the id in aletvariable outside the handlers, so that every handler can use it.setInterval(function () { ... }, 1000)runs the function every second untilclearInterval(timer)stops it. A variable outside the function remembers what changes between the runs, such as the seconds left.button.disabled = true;disables a button while the page is busy, andfalseenables it again.- A function that takes a while returns a Promise, a value that arrives later.
awaitwaits for the value, and it works only in a function markedasync. Withoutawait, you get the Promise itself, and the page shows[object Promise]. - An
asyncfunction can wait several times, one step after another, for example withawait wait(1000);. The rest of the page keeps working in the meantime. - A message such as
Loading…before theawaittells the user that the page is waiting. - When a Promise fails,
awaitthrows an error.try { ... } catch (error) { ... }catches it, anderror.messageis its text.finallyruns at the end in both cases.
In the next lesson, Data from a Server, your pages will load data from a server with fetch(), which returns a Promise too, so you'll use await there all the time.
But first, some practice with timers: a lightning quiz, in which the player has just 2 seconds to answer. This time, script.js is empty, and you'll write the whole program yourself.
Instructions
When the button #start is clicked, set a timer: 2 seconds later, #result shows Time's up!. Save the timer in a variable timer created with let outside the handler; you'll need it in a moment.
When #jupiter is clicked, show Correct! in #result and cancel the timer, so that Time's up! doesn't replace it.
Mars and Venus are wrong answers: when either of them is clicked, show Wrong! It's Jupiter. and cancel the timer too.