栏目分类:
子分类:
返回
名师互学网用户登录
快速导航关闭
当前搜索
当前分类
子分类
实用工具
热门搜索
名师互学网 > IT > 软件开发 > Web开发 > JavaScript

javascript实现的简单计时器

JavaScript 更新时间: 发布时间: IT归档 最新发布 模块sitemap 名妆网 法律咨询 聚返吧 英语巴士网 伯小乐 网商动力

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.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 来获取当前时间

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

转载请注明:文章转载自 www.mshxw.com
本文地址:https://www.mshxw.com/it/101571.html
我们一直用心在做
关于我们 文章归档 网站地图 联系我们

版权所有 (c)2021-2022 MSHXW.COM

ICP备案号:晋ICP备2021003244-6号