What Runs First

setTimeout() doesn't pause the program. It only sets the timer and hands it the function, and the script goes on with the next line straight away. What do you think this prints?

console.log("The water is boiling.");

setTimeout(function () {
    console.log("The tea is ready!");
}, 3000);

console.log("Waiting for the tea…");
The water is boiling.
Waiting for the tea…
The tea is ready!

The last line comes three seconds after the other two. JavaScript runs the first console.log(), sets the timer and runs the second console.log() right away. Only when the three seconds are up does the browser call the function of the timer. It would be the same even with 0 milliseconds: the function of a timer runs only after the code that is running now has finished.

So everything that should happen after the wait must be inside the function of the timer. Lines below setTimeout() run immediately:

setTimeout(function () {
    statusText.textContent = "The tea is ready!";
}, 3000);
statusText.textContent = "Enjoy!"; // Runs right away, not after 3 seconds

This page first says Enjoy!, and The tea is ready! appears 3 seconds later.

In this exercise, you'll also use the property disabled of a button. After button.disabled = true;, the button turns gray, and clicking it does nothing; button.disabled = false; makes it work again. That's handy while a page waits for something, so that nobody starts the same thing twice.

Instructions

Click Brew tea: the page says Your tea is ready! straight away, because the line after setTimeout() doesn't wait. Move that line into the function of the timer, so that the tea is ready 2 seconds after the click.

While the tea is brewing, nobody should start another one: at the start of the handler, disable brewButton with brewButton.disabled = true;, and when the tea is ready, enable it again.

Start programming for free

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

Or sign up with:

Back

2/9

Next