javascript实现的简单计时器
javascript实现的简单计时器
发布时间:2016-12-30 来源:查字典编辑
摘要:最近写了很多微信端的互动小游戏,比如下雪花限时点击赢取奖品,限时拼图,限时答题等,都是些限时‘游戏'(其实算不上游戏,顶多算是具有一点娱乐性...

最近写了很多微信端的互动小游戏,比如下雪花 限时点击 赢取奖品,限时拼图,限时答题等,都是些限时‘游戏'(其实算不上游戏,顶多算是具有一点娱乐性的小互动而已)

上面出现了4个限时,对,没错,这里记录的就是最近写的 ‘计时器' ...

恩 , 计时器 就一个setInterval 或 setTimeout 即可实现 ,代码不会超过十行!

但是不防抱着没事找事的心态,来写个能复用的计时器

1.能倒计时 也能顺计时

2.复位、暂停、停止,启动功能

//计时器 window.timer = (function(){ function mod(opt){ //可配置参数 都带有默认值 //必选参数 this.ele = typeof(opt.ele)=='string'?document.getElementById(opt.ele):opt.ele;//元素 //可选参数 this.startT = opt.startT||0;//时间基数 this.endT = opt.endT=='undefined'?24*60*60:opt.endT;//结束时间 默认为一天 this.setStr = opt.setStr||null;//字符串拼接 this.countdown = opt.countdown||false;//倒计时 this.step = opt.step||1000; //不可配置参数 this.timeV = this.startT;//当前时间 this.startB = false;//是否启动了计时 this.pauseB = false;//是否暂停 this.init(); } mod.prototype = { constructor : 'timer', init : function(){ this.ele.innerHTML = this.setStr(this.timeV); }, start : function(){ if(this.pauseB==true||this.startB == true){ this.pauseB = false; return; } if(this.countdown==false&&this.endT<=this.cardinalNum){ return false; }else if(this.countdown==true&&this.endT>=this.startT){ return false; } this.startB = true; var v = this.startT, this_ = this, anim = null; anim = setInterval(function(){ if(this_.startB==false||v==this_.endT){clearInterval(anim);return false} if(this_.pauseB==true)return; this_.timeV = this_.countdown?--v:++v; this_.ele.innerHTML = this_.setStr(this_.timeV); },this_.step); }, reset : function(){ this.startB = false; this.timeV = this.startT; this.ele.innerHTML = this.setStr(this.timeV); }, pause : function(){ if(this.startB == true)this.pauseB = true; }, stop : function(){ this.startB = false; } } return mod; })();

调用方式:

var timerO_1 = new timer({ ele : 'BOX1', startT : 0, endT : 15, setStr : function(num){ return num+'s'; } }); var timerO_2 = new timer({ ele : 'BOX2', startT : 30, endT : 0, countdown : true, step : 500, setStr : function(num){ return num+'s'; } });

这里传入的方法 setStr是计数器计算的当前时间写入ele前的字符串处理

countdown是否为倒计时 默认为顺计时

可以通过 timerO.timeV 来获取当前时间

以上所述就是本文的全部内容了,希望大家能够喜欢。

推荐文章
猜你喜欢
附近的人在看
推荐阅读
拓展阅读
相关阅读
网友关注
最新Javascript教程学习
热门Javascript教程学习
编程开发子分类