ruk·si

🍦 JavaScript
Interval Ticker

Updated at 2012-11-12 10:19

This is a small snippet that runs code on specific intervals for specific number of times and then cleans itself up.

var count = 0;
var timer = setInterval(function() {
  if ( count < 5 ) {
    console.log( 'Timer call: ', count );
    count++;
  }
  else {
    console.assert(
      count === 5,
      'Count came via a closure, accessed each step.'
    );
    console.assert(
      timer,
      'The timer reference is also via a closure.'
    );
    clearInterval( timer );
    console.log('Timer has been cleaned!');
  }
}, 100);

// =>
// Timer call: 0
// Timer call: 1
// Timer call: 2
// Timer call: 3
// Timer call: 4
// Timer has been cleaned!