Doing Something Later
So far, your scripts have done things at two moments: when the page loads, and when the user does something, such as clicking, typing or sending a form. Often, though, something should happen after a while: a message disappears a few seconds after it appears, an offer pops up, a reminder rings. For this, JavaScript has the function setTimeout(), a timer:
setTimeout(function () {
console.log("Two seconds have passed.");
}, 2000);setTimeout() takes two arguments: a function, and how long to wait before it runs the function, in milliseconds (thousandths of a second). 1000 milliseconds is one second, so 2000 is two seconds. Notice the end: } closes the function, then come a comma and the number, and ) closes the parentheses of setTimeout(.
It's like addEventListener(): the script only hands the function over, and the browser calls it later, this time when the time is up, and only once.
You can set a timer when the page loads or in a handler. This one empties a message two seconds after a click:
saveButton.addEventListener("click", function () {
message.textContent = "Saved!";
setTimeout(function () {
message.textContent = "";
}, 2000);
});The function can also be one you've defined before, passed by its name:
function hideMessage() {
message.textContent = "";
}
setTimeout(hideMessage, 2000);Typical mistakes:
setTimeout(hideMessage(), 2000): with the parentheses,hideMessage()runs right away, andsetTimeout()gets what it returned instead of the function. As withaddEventListener(), pass the function without().setTimeout(hideMessage, 2): the time is in milliseconds, not seconds, so the timer waits two thousandths of a second, and the message disappears before anyone can read it.
The page in this exercise has the class hidden in its CSS, with the rule display: none;, which hides an element. Remove the class, and the element shows.
Instructions
One second after the page loads, show the offer: set a timer with setTimeout() for 1000 milliseconds, and in its function, remove the class hidden from offer. Click Run and watch the offer appear.
The message should disappear 2 seconds after the click: in the handler, below the line that shows it, set a timer for 2000 milliseconds that sets the text of message to an empty text, "".