quinta-feira, 16 de janeiro de 2014

A Timer object with angular.js

The problem

Angular JS is probably the best javascript framework around. Simple things are simple and complicated things are possible. As with any other framework in any language, one has to adapt the thought patterns around the intricacies and the peculiarities of the language and the library. One has to take time to learn Angular, but once it is finally understood, the productivity is enhanced.

I have done some web pages with angular. For one I wanted a timer object that I coud stop, start, set the period and the method at will. For instance, within a controller or a directive or any other Angular object:

var timer = new Timer(5000, myFunction, $timeout).start()

This will start the timer and run myFunction every five seconds.

timer.delay(3);

This function will delay the firing of the timer for 3 periods (in the case, 15 seconds.

The rest of the functions should be obvious.

The implementation

The code should be simple to just copy and paste. It uses the $timeout global object from Angular, som make sure angular.js is imported into the page.

var Timer = function(period, meth, $timeout) {
  var tID = null;
  var tPeriod = period || 5000;
  var tDelay = 0;
  var tMeth = meth || null;


  function delay(periods) {
    tDelay = periods;
    return this;
  }

  function setPeriod(period) {
    tPeriod = period || 5000;
    return this;
  }

  function setMethod(meth) {
    tMeth = meth || null;
    return this;
  }

  function stop () {
    if (typeof(tID) != null) {
      $timeout.cancel(tID);
      tID = null;
    }
    return this;
  }

  function start() {
    tID = $timeout(function () {
       if (tDelay) {
         tDelay -= 1;
       } else {
         if (tMeth) {
           tMeth();
         }
       }
       start();
    }, tPeriod);
    return this;
  }

  function restart() {
    stop();
    start();
    return this;
  }

  return {
    'delay': delay,
    'restart': restart,
    'setMethod': setMethod,
    'setPeriod': setPeriod,
    'start': start,
    'stop': stop
  }
}

As always, suggestions are appreciated.

Sem comentários:

Enviar um comentário