Light12306/RwTicketAssistantV2/app/air/js/util/Timer.js

127 lines
2.4 KiB
JavaScript
Raw Normal View History

/**
* 定时器
* @class Timer
* @constructor
* @param {String} id 定时器的唯一标识
* @param {Number} delay 初次运行的延迟时间
* @param {Number} interval 每次运行的间隔时间
* @param {Object} callback 定时执行的方法参数为Timer本身
* @param {mix} context 传入回调方法的上下文
*/
var Timer = function(id, delay, interval, callback, context) {
this.id = id;
this.delay = delay;
this.interval = interval;
this.callback = callback;
this.context = context;
};
/**
* 开始执行定时器
* @method start
*/
Timer.prototype.start = function() {
if (this.timer !== undefined) {
clearTimeout(this.timer);
delete this.timer;
}
var _this = this;
var execute = function() {
_this.callback(_this);
//在回调函数中被中止
if (_this.timer !== undefined) {
_this.timer = setTimeout(execute, _this.interval);
}
};
this.timer = setTimeout(execute, this.delay);
};
/**
* 中止定时器
* @method halt
*/
Timer.prototype.halt = function() {
clearTimeout(this.timer);
delete this.timer;
};
/**
* 定时器是否在运行中
* @method isRunning
* @return Boolean
*/
Timer.prototype.isRunning = function() {
return this.timer !== undefined;
};
/**
* 定时器管理这是一个单例
* @class TimerManager
* @constructor
*/
var TimerManager = function() {
var instance = this;
this.timers = {};
TimerManager = function() {
return instance;
};
};
/**
* 添加一个定时器
* @method addTimer
* @param {Object} 要添加的Timer
*/
TimerManager.prototype.addTimer = function(timer) {
if (this.timers[timer.id] === undefined) {
this.timers[timer.id] = timer;
}
return this;
};
/**
* 根据唯一标识获取定时器
* @method getTimer
* @param {String} id 定时器的id
* @return {Object}
*/
TimerManager.prototype.getTimer = function(id) {
return this.timers[id];
};
/**
* 删除一个定时器
* @method halt
* @param {String} id 定时器的id
*/
TimerManager.prototype.deleteTimer = function(id) {
if (this.timers[id] !== undefined) {
this.timers[id].halt();
}
delete this.timers[id];
};
/**
* 定时器全部开始运行
* @method startAll
*/
TimerManager.prototype.startAll = function() {
for (id in this.timers) {
this.timers[id].start();
}
};
/**
* 定时器全部中止
* @method haltAll
*/
TimerManager.prototype.haltAll = function() {
for (id in this.timers) {
this.timers[id].halt();
}
};