JavaScript clearInterval() method

As long as you stored them in a variable, the looping countdown timers launched with setInterval() can be stopped using the clearInterval() method: the argument you pass is the timer name. In this snippet, we keep track of the number of times the timer ran, and cancel it after 5 runs: // Initialize counter and future timer as global variables:var counter = 0, timer = null;

Caveat: ensure that your variables counter and timer are global in scope (variables declared inside functions won't work - JavaScript automatically deletes these when you exit the function body).

Sister methods:• setTimeout() starts a single countdown timer, cancellable by clearTimeout() before it expires.• setInterval() launches a series of recurring timers that run until stopped with clearInterval().