天天看點

【javascript】定時器元件

定時器元件,類似定時器管理。

'use strict';
module.exports = function() {
    this.timer = {};
    this.config = {};
    // 初始化參數
    this.init = function(opts) {
        var id = opts.id;
        this.config[id] = opts;
        this.config[id].interval = this.config[id].interval || 1;
        this.config[id].begin = opts.begin || 0;
        this.config[id].end = opts.end || 0;
        this.config[id].step = opts.step || 1;
        this.config[id].type = opts.begin < opts.end ? 1 : 0;
        this.clear([id]);
        this.start(id);
    };
    // 開啟定時器
    this.start = function(id) {
        var self = this;
        var type = this.config[id].type;
        var interval = this.config[id].interval;
        var step = this.config[id].step;
        var cb = this.config[id].callback;
        // 先執行一次回調
        cb && cb(this.config[id].begin);
        type ? this.config[id].begin += step : this.config[id].begin -= step;
        this.timer[id] = setInterval(function() {
            self.loop(id);
        }, interval * 1e3);
    };
    this.loop = function(id) {
        var begin = this.config[id].begin;
        var end = this.config[id].end;
        var step = this.config[id].step;
        var cb = this.config[id].callback;
        var endFunc = this.config[id].endFunc;
        cb && cb(this.config[id].begin);
        if (this.config[id].type) {
            if (begin > end) {
                this.clear([id]);
                endFunc && endFunc();
            } else {
                this.config[id].begin += step;
            }
        } else {
            if (begin < end) {
                this.clear([id]);
                endFunc && endFunc();
            } else {
                this.config[id].begin -= step;
            }
        }
    };
    // 更新定時器參數
    this.update = function(opts) {
        this.config[opts.id] = _.extend({}, this.config[opts.id], opts);
    };
    // 清除某個(多個或者全部)定時器
    this.clear = function(ids) {
        var self = this;
        if (ids && ids.length) {
            _.each(ids, function(id) {
                clearInterval(self.timer[id]);
            });
        } else {
            _.each(self.timer, function(v) {
                clearInterval(v);
            });
        }
    };
};      

參數說明

  • opts.id(String): 定時器id;
  • opts.interval(Number, 機關s, 預設1): 每次輪詢時間,比如 1;
  • opts.callback: 回調函數;
  • opts.begin(Number): 起始值;
  • opts.end(Number): 終點值;
  • opts.step 遞增/遞減數值。
  • opts.endFunc 定時器結束後觸發回調(新增)

如何使用

var timer = new Timer();
timer.init({
    id: 'count',
    begin: 60,
    callback: function(count) {
        if (count >= 0) {
            // do something...
        }
    },
    endFunc: function() {
        // do something...
    }
});      

PS

_.each() 和 _.extend() 是 underscore.js 文法,有關 underscore.js 文檔點此檢視。

繼續閱讀