[记录] javascript 对象中使用setTimeout
参考:Javascript对象中关于setTimeout和setInterval的this介绍
使用最后一个方法终于弄好了,简直了,在对象中使用setTimeout原来是这样的
做的是分钟倒计时,倒数3分钟
1 function clock(){ 2 3 this.min = 3; //倒数的分钟 4 this.speed = 1000; //setTimeout时间 5 var timeId = ""; //保存setTimeout对象 6 this.time = this.min * 60;//3分钟等于180s 7 this.move = function(){ 8 var that = this;//保存当前对象this 9 this.time = parseInt(that.time); 10 var minute = 0; //分 11 var seconds = 0; //秒 12 13 14 if(this.time > 60){ 15 minute = parseInt(that.time / 60); 16 seconds = parseInt(that.time % 60); 17 }else{ 18 minute = 0; 19 seconds = parseInt(that.time % 60) 20 } 21 22 23 24 var txt = ((minute < 10) ? "0" + minute : minute) + " : " + ((seconds < 10) ? "0" + seconds : seconds); 25 26 timeId = setTimeout(function(){ 27 that.move(); 28 },that.speed); 29 30 console.log(that.time); 31 that.time--; 32 console.log(txt); 33 34 if(that.time <= 0){ 35 clearTimeout(timeId); 36 }; 37 }, 38 this.stop = function(){ 39 clearTimeout(timeId); 40 } 41 }
使用:
1 var eva3_clock = new clock(); 2 eva3_clock.move();