javascript学习之PeriodicalExecuter

var PeriodicalExecuter=Class.create();
PeriodicalExecuter.prototype={
  initialize:function(callback,frequency){
    this.callback=callback;
    this.frequency=frequency;
    this.currentlyExecuting=false;
    this.registerCallback();
  },
  registerCallback:function(){
    this.timer=setInterval(this.onTimerEvent.bind(this),this,frequency*1000)
  },
  stop:function(){
    if(!this.timer)return;
    clearInterval(this.timer);
    this.timer=null;
  },
  onTimerEvent:function(){
    if(!this.currentlyExecuting){
      try{
        this.currentlyExecuting=true;
        this.callback(this);
      }finally{
         this.currentlyExecuting=false;
      }
    }
  }
}
/*这是一个定时类,它可以定时的去调用某一个函数,当我们要停止时,只需要改变它的状态 ,就取消函数的调用
例如:var i=0;
			function fn(){
				document.write(new Date()+'<br>')
				if(i++>100)
					a.stop();
			}
			
			  var a=new PeriodicalExecuter(fn,0.1)
*/

你可能感兴趣的:(javascript学习之PeriodicalExecuter)