参考:Javascript对象中关于setTimeout和setInterval的this介绍
使用最后一个方法终于弄好了,简直了,在对象中使用setTimeout原来是这样的
做的是分钟倒计时,倒数3分钟
function clock(){ this.min = 3; //倒数的分钟
this.speed = 1000; //setTimeout时间
var timeId = ""; //保存setTimeout对象
this.time = this.min * 60;//3分钟等于180s
this.move = function(){
var that = this;//保存当前对象this
this.time = parseInt(that.time);
var minute = 0; //分
var seconds = 0; //秒 if(this.time > 60){
minute = parseInt(that.time / 60);
seconds = parseInt(that.time % 60);
}else{
minute = 0;
seconds = parseInt(that.time % 60)
} var txt = ((minute < 10) ? "0" + minute : minute) + " : " + ((seconds < 10) ? "0" + seconds : seconds); timeId = setTimeout(function(){
that.move();
},that.speed); console.log(that.time);
that.time--;
console.log(txt); if(that.time <= 0){
clearTimeout(timeId);
};
},
this.stop = function(){
clearTimeout(timeId);
}
}
使用:
var eva3_clock = new clock();
eva3_clock.move();