// Initialize counter and future timer as global variables:
var counter = 0, timer = null;
// Launch time: greet visitor every second, increment counter, check status
timer = setInterval( "alert('Hello!'); ++counter; checkTimer()", 1000 );
function checkTimer() {
if( counter == 5 )
clearInterval( timer ); // Interval stops running
}
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().