我最近寫了我自己的股票類,可隨時將其擴展到您的需求:
// An advanced timeout class which also calculates the current progress
var Ticker = function(start, duration, callback) {
var _this = this;
this.start = start;
this.duration = duration;
// TODO easing options
this.reverse = false;
this.auto_reset = false;
this.auto_reverse = false;
this.callback = callback ? callback : null;
this.timeout = callback ? setTimeout(function() {
_this.callback();
if (_this.auto_reset || _this.auto_reverse) { _this.reset(); }
}, this.duration) : null;
};
Ticker.prototype.status = function() {
var end = this.start + this.duration;
var current = +new Date;
var duration = end - this.start;
var difference = current - this.start;
var progress = this.reverse ? 1 - (difference/duration) : (difference/duration);
if (current >= end) { progress = this.reverse ? 0 : 1; }
return progress;
};
Ticker.prototype.reset = function() {
if (this.auto_reverse) { this.reverse = this.reverse ? false : true; }
var _this = this;
this.timeout = this.callback ? setTimeout(function() {
_this.callback();
if (_this.auto_reset || _this.auto_reverse) { _this.reset(); }
}, this.duration) : null;
this.start = +new Date;
};
用法:
// Tickers every 1000 ms
var ticker = new Ticker(+new Date, 1000, function() {
console.log("done");
});
ticker.auto_reset = true;
您還可以得到由目前的進展調用status()
方法。
它返回一個數字,表示當前進度從0.0
到1.0
。