Some things should happen later, not right now. setTimeout(fn, ms) asks the browser to call the function fn once, after ms milliseconds (3000 ms is 3 seconds). It doesn't wait: the next line runs at once, and the function runs when the time is up.
const banner = document.querySelector("#banner");
banner.textContent = "Welcome back!";
const bannerTimer = setTimeout(() => {
banner.textContent = "";
}, 5000);
setTimeout gives back a number, the timer's id. clearTimeout(id) cancels that timer before it fires. Keep the id in a variable declared with let outside the function, so the next call can still find it and cancel it.
The check's clock only moves when it says so. It clicks Add to cart in Mug, lets 2000 ms pass, clicks Add to cart in Lamp, then lets 2000 ms and 1000 ms pass. Your cart must show:
> click "Add to cart" in "Mug" → text: Mug added > 2000 ms pass → text: Mug added > click "Add to cart" in "Lamp" → text: Lamp added > 2000 ms pass → text: Lamp added > 1000 ms pass → (the message is gone)
Your task: write a function showMessage(text) that shows the text in #message and empties it 3000 ms later, and call it from addToCart with the product's name and " added". Each new message cancels the previous timer, so its 3 seconds start again.
Assignment
Follow the Coding Tutorial to show "Mug added" after each click and hide it with a timer that restarts on every click.
Hint
Without clearTimeout, the Mug timer still fires 3 seconds after the Mug click and empties "Lamp added" too early. Cancel the old timer first, then start the new one.
Free plan: 30 tutor messages. PRO is unlimited.
