您好,欢迎访问一九零五行业门户网

javascript实现的简单计时器_javascript技巧

最近写了很多微信端的互动小游戏,比如下雪花 限时点击 赢取奖品,限时拼图,限时答题等,都是些限时‘游戏'(其实算不上游戏,顶多算是具有一点娱乐性的小互动而已)
上面出现了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.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 来获取当前时间
以上所述就是本文的全部内容了,希望大家能够喜欢。
其它类似信息

推荐信息