Canceling an Alarm with clearTimeout()

Sometimes you'll want to cancel a setTimeout(). Imagine a riddle game in which a player has 10 seconds to guess the riddle's answer. If players don't answer the riddle correctly in 10 seconds, they are sent to a page that gives them the answer. If they do figure out the answer in time, they are congratulated. You could write this game by setting a setTimeout() to send players to the answer page in 10 seconds. If they answer the riddle correctly before the 10 seconds expire, you need to cancel the setTimeout() so they don't end up on the answer page.

To cancel a setTimeout(), you first need to name the time-out by storing it in a variable:

var my_timeout = setTimeout("goToAnswerPage();", 10000);

This line creates ...

Get The Book of JavaScript, 2nd Edition now with the O’Reilly learning platform.

O’Reilly members experience books, live events, courses curated by job role, and more from O’Reilly and nearly 200 top publishers.