Canceling a Timer

Many email apps let you take a message back: after you click Send, they wait a few seconds, and if you click Undo in the meantime, the message never goes. That's a timer that can be canceled.

setTimeout() returns a number, the timer's id. Save it in a variable, and you can cancel the timer with clearTimeout(): its function then never runs.

let sendTimer;

sendButton.addEventListener("click", function () {
    statusText.textContent = "Sending in 3 seconds…";
    sendTimer = setTimeout(function () {
        statusText.textContent = "Sent.";
    }, 3000);
});

undoButton.addEventListener("click", function () {
    clearTimeout(sendTimer);
    statusText.textContent = "Not sent.";
});

The variable sendTimer is created outside both handlers, so that both can use it: one saves the timer in it, the other cancels the timer. That's the rule you know from the click counter. It's created with let, because each click on Send saves a new timer in it. At first, it has no value, so it holds undefined, and clearTimeout(undefined) simply does nothing. A click on Undo before Send causes no error.

Typical mistakes:

  • const sendTimer = setTimeout(...) inside the handler of Send: the variable then exists only in that handler, and the handler of Undo ends with ReferenceError: sendTimer is not defined.
  • clearTimeout() cancels only the timer whose id it gets. If Send is clicked twice, two timers are running, and the variable holds only the second one.

Instructions

Make the Abort button work. Above the handler, create a variable launchTimer with let, and save in it the timer that the handler of launchButton sets. When abortButton is clicked, cancel the timer with clearTimeout() and show Launch aborted. in statusText.

Try clicking Launch twice and then Abort: the rocket takes off anyway. Each click set a timer of its own, and launchTimer holds only the second one. Fix it: at the start of the handler of launchButton, cancel the previous timer with clearTimeout(launchTimer).

Start programming for free

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

Or sign up with:

Back

3/9

Next