[记录] javascript 对象中使用setTimeout

本文详细介绍了在JavaScript对象中使用setTimeout实现分钟倒计时的方法,着重解析了如何正确处理this指向问题,确保倒计时功能的正常运行。

参考: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();

 

转载于:https://www.cnblogs.com/fsong/p/5101856.html

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值