JavaScript Timer Class

Author: Domenico Strazzullo
nst@dotuscomus.com
Creative Commons License
This work is licensed under a Creative Commons Attribution-No Derivative Works 3.0 Unported License.

FEATURES

Download Timer.zip

DESCRIPTION

This Timer class provides an API for full control over timers using the setTimeout() and setInterval() methods of the window object. For description, use and examples see the article http://www.svgmagazine.com/nov2011/js_timer.html in the November 2011 issue of SVG magazine.

TIMER CLASS

var Timer = function () {		
  var self,
      handle;

  return {
    initialize : function () {
      var o = arguments[0];
      for (var prop in o) this[prop] = o[prop];
      var f = "frequence" in this,
          d = "delay" in this;

      self = this;
      handle = this.handle || this;
      if (handle != this) handle.callback = this.callback;

      if (f && d) this.timeout = window.setTimeout(this.setInterval, this.delay);
      else if (f) this.setInterval();
      else this.timeout = window.setTimeout(function () {handle.callback(self);}, this.delay);
      return this;
    },

    setInterval : function () {
      self.interval = window.setInterval(function () {handle.callback(self);}, self.frequence);
    },

    clear : function () {
      if (this.timeout) window.clearTimeout(this.timeout);
      if (this.interval) window.clearInterval(this.interval);
      this.timeout = this.interval = null;
      if (this.destroy) Timer.destroy(handle, this.destroy);
    }
  }
};

Timer.destroy = function (handle, name) {
  if (handle[name]) delete handle[name];
  else if (name in window) {
    if (! delete window[name]) window[name] = null;
  }
};