Clockmaker.js

Flexible Javascript timers which can be paused and modified on-the-fly.

Installation:

$ npm install --save clockmaker # node
$ bower install --save clockmaker # browser

Download:

clockmaker.min.js <1KB gz

Single-run timer

Timer(function(timer) {
  console.log(timer.getDelay() + ' millseconds, ' + timer.getNumTicks() + ' ticks.');
}, 2000)

Repeating timer

Timer(function(timer) {
  console.log(timer.getDelay() + ' millseconds, ' + timer.getNumTicks() + ' ticks.');
}, 2000, { repeat: true })

Change timer interval

Timer(function(timer) {
  var delay = timer.getDelay();
  console.log(timer.getDelay() + ' millseconds, ' + timer.getNumTicks() + ' ticks.');
  timer.setDelay(delay + 500);
}, 1000, { repeat: true })

Synchronize to now

This resets the timer's internal time counter to start from the present moment.

Timer(function(timer) {
  console.log(timer.getDelay() + ' millseconds, ' + timer.getNumTicks() + ' ticks.');
}, 2000, { repeat: true })

Handler 'this' context

Timer(function() {
  // this == document
  console.log('This page has ' + this.querySelectorAll('.examples > section').length + ' examples!');
}, 500, { thisObj: document })

Error handling

Timer(function() {
  throw new Error('You should see this!');
}, 500, { onError: console.error })

Asynchronous handler

Timer(function(timer, cb) {
  console.log(timer.getDelay() + ' millseconds, ' + timer.getNumTicks() + ' ticks.');
  // defer the callback
  Timer(function() {
    cb();
  }, 2000).start(); 
}, 500, { async: true, repeat: true })

Multiple timers

new Timers()
  .add(
    Timer(function(timer) {
      console.log('Timer 1: ' + timer.getNumTicks() + ' ticks');
    }, 1000, { repeat: true })
  )
  .add(
    Timer(function(timer) {
      console.log('Timer 2: ' + timer.getNumTicks() + ' ticks');
    }, 3000, { repeat: true })
  )