首頁 > web前端 > js教程 > 主體

javascript實作的簡單計時器_javascript技巧

WBOY
發布: 2016-05-16 15:49:44
原創
1288 人瀏覽過

最近寫了很多微信端的互動小遊戲,比如下雪花限時點擊贏取獎品,限時拼圖,限時答題等,都是些限時'遊戲'(其實算不上游戲,頂多算是具有一點娛樂性的小互動而已)

上面出現了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&#63;--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 來取得當前時間

以上所述就是本文的全部內容了,希望大家能夠喜歡。

相關標籤:
來源:php.cn
本網站聲明
本文內容由網友自願投稿,版權歸原作者所有。本站不承擔相應的法律責任。如發現涉嫌抄襲或侵權的內容,請聯絡admin@php.cn
熱門教學
更多>
最新下載
更多>
網站特效
網站源碼
網站素材
前端模板
關於我們 免責聲明 Sitemap
PHP中文網:公益線上PHP培訓,幫助PHP學習者快速成長!