html5中文学习网

您的位置: 首页 > 网站及特效实例 > javascript特效 » 正文

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

[ ] 已经帮助:人解决问题

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

上面出现了4个限时,对,没错,这里记录的就是最近写的 ‘计时器' ...x97HTML5中文学习网 - HTML5先行者学习网

恩 , 计时器 就一个setInterval 或 setTimeout 即可实现 ,代码不会超过十行!x97HTML5中文学习网 - HTML5先行者学习网

但是不防抱着没事找事的心态,来写个能复用的计时器x97HTML5中文学习网 - HTML5先行者学习网

1.能倒计时 也能顺计时x97HTML5中文学习网 - HTML5先行者学习网

2.复位、暂停、停止,启动功能x97HTML5中文学习网 - HTML5先行者学习网
x97HTML5中文学习网 - HTML5先行者学习网

//计时器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;})(); 

调用方式:x97HTML5中文学习网 - HTML5先行者学习网
x97HTML5中文学习网 - HTML5先行者学习网

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前的字符串处理x97HTML5中文学习网 - HTML5先行者学习网

countdown是否为倒计时 默认为顺计时x97HTML5中文学习网 - HTML5先行者学习网

可以通过 timerO.timeV 来获取当前时间x97HTML5中文学习网 - HTML5先行者学习网

以上所述就是本文的全部内容了,希望大家能够喜欢。x97HTML5中文学习网 - HTML5先行者学习网

(责任编辑:)
推荐书籍
推荐资讯
关于HTML5先行者 - 联系我们 - 广告服务 - 友情链接 - 网站地图 - 版权声明 - 人才招聘 - 帮助