javascript實現的簡單計時器,javascript計時器

來源:互聯網
上載者:User

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.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 來擷取目前時間

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

聯繫我們

該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在5個工作日內處理。

如果您發現本社區中有涉嫌抄襲的內容,歡迎發送郵件至: info-contact@alibabacloud.com 進行舉報並提供相關證據,工作人員會在 5 個工作天內聯絡您,一經查實,本站將立刻刪除涉嫌侵權內容。

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.