`

javascript centralized timers

阅读更多

a centralized timers has benefit over non-centralized timers. the benefit including .

 

1. have one timers object that excute per page at a time. 

2. you can start, stop, resume the timer 

3. process of removing the timer callback is trivilized 

 

 

and one special note about the javascipt garbage collection concering about timers. Increasing the number of simutaneous timer is likely to increase the likelihood of a garbage collection in the browser. this is roughly when the browser goes through and tries to tie up loose ends (removing unused variables, objects, etc...)

 

below show the framework code that has the centralized timer. 

 

 

/**************************************
*@Summary
*  this is the central timer declaration which you can cetralized manage all timer object
*
*  the benifit of the centralized timer object is that 1. only one timer running per page at a time. 2. pause and resume 3. process of removing callbacks is trivilized
*
* special note on that increasing number of simutaneous timers is likely to increase the likelihood of a garbge collection in the browser. Roughly speaking this is when the browser
* goes through and tries to tie up any loose ends (removing unused variables, objects, etc.).
* @Usage:
*   


* @TODO:
* test it.  
***************************************/

var timers = {

  timerID: 0,
  timers: [],
  start: function () {
    if (this.timerID) {
      return;
    }
    (function () {
      for (var i = 0; i < timers.timers.length; i++) {
        if (timers.timers[i]() === false) {
          timers.timers.splice(i, 1);
        }
      }
      // the return value of setTimeout is the timerId
      timers.timerID = setTimeout(argument.callee, 0);
    })();
  },
  stop: function () {
    clearTimeout(this.timerID);
    // you have to explicitly set the stored timeId value to 0
    this.timerID = 0;
  },
  add: function () {
    this.timers.push(fn);
    this.start();
  }
};
 

 

the test code is yet to come. 

分享到:
评论

相关推荐

Global site tag (gtag.js) - Google Analytics