利用闭包实现一个javascript的Timer(定时器)

时间: 2010-01-26 / 分类: Javascript / 浏览次数: 25 views / 0个评论 发表评论
var Timer = function(obj){
var t = null;
var interval = 1000;
var start = function(period, callback){
     if(t) clearTimeout(t);
     t = setTimeout(function(){ if(callback) callback.call(obj);}, period);
}
var stop = function(){
    clearTimeout(t);
}
var repeat = function(period, callback){
     if(t) clearTimeout(t);
     t = setTimeout(function(){ if(callback) callback.call(obj); repeat(period, callback);}, period);
}

this.start = start;
this.stop = stop;
this.repeat = repeat;
}

var obj = {
   name: "timer1"
};

var time = new Timer(obj);
//time.start(1000, function(){ alert(this.name);});
time.repeat(1000, function(){ alert(this.name);});

发表评论

您的昵称 *

您的邮箱 *

您的网站