PeriodicalExecuter类

PeriodicalExecuter 周期执行器 其构造函数为new PeriodicalExecuter(handler,周期); 只有一个方法stop()

//给个时钟

实现代码
var pe=null;
function run()
{
    $("clock").innerHTML=(new Date());
}

function createPeriodicalExecuter()
{
    pe =new PeriodicalExecuter(run,1);
}

function stopPeriodicalExecuter()
{
    pe.stop();
}

Event.observe(window,'load',run);
Event.observe(window,'load',createPeriodicalExecuter);

给出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;
           }
        }
    }
}