北漂IT民工 的博客

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


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);});