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, and clearTimeout(timer) cancels the timer. Keep the id in a let variable outside the handlers, so that every handler can use it.
  • setInterval(function () { ... }, 1000) runs the function every second until clearInterval(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, and false enables it again.
  • A function that takes a while returns a Promise, a value that arrives later. await waits for the value, and it works only in a function marked async. Without await, you get the Promise itself, and the page shows [object Promise].
  • An async function can wait several times, one step after another, for example with await wait(1000);. The rest of the page keeps working in the meantime.
  • A message such as Loading… before the await tells the user that the page is waiting.
  • When a Promise fails, await throws an error. try { ... } catch (error) { ... } catches it, and error.message is its text. finally runs 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.

Start programming for free

By signing up, you agree to the Terms of Service and Privacy Policy.

Or sign up with:

Back

9/9

Next