Home Tech Geek Web Development Solution to: How do I cancel a setTimeout() call in Javascript?

Get social!

Solution

Use clearTimeout().

Set timeout function:

var timer = setTimeout(function() { alert('hi there') }, 5000);

To cancel it:

clearTimeout(timer);

Here’s a JS Fiddle illustrate:

http://jsfiddle.net/drodrig/yfn48/

Just click the “Start Timer” link, wait 5 seconds, and you should get an alert box. Close the alert, click the “Start Timer” link again. This time click the “Stop Timer” link within the 5 seconds and you won’t see the alert box.

Bad Behavior has blocked 86 access attempts in the last 7 days.