@motorcycle/test
Version:
Testing functions for Motorcycle.ts
90 lines • 2.82 kB
JavaScript
/**
* A Timer instance with control over how time progresses.
*
* @name VirtualTimer
* @example
* import { VirtualTimer } from '@motorcycle/test'
*
* const timer = new VirtualTimer()
*
* timer.setTimer(() => console.log('Hello'), 100)
*
* timer.tick(100)
*/
var VirtualTimer = /** @class */ (function () {
function VirtualTimer() {
this.time = 0;
this.targetTime = 0;
this.currentTime = Infinity;
this.task = void 0;
this.active = false;
this.running = false;
this.key = {};
this.promise = Promise.resolve();
}
VirtualTimer.prototype.now = function () {
return this.time;
};
VirtualTimer.prototype.setTimer = function (fn, delay) {
if (this.task !== void 0)
throw new Error('Virtualtimer: Only supports one in-flight task');
this.task = fn;
this.currentTime = this.time + Math.max(0, delay);
if (this.active)
this.run();
return this.key;
};
VirtualTimer.prototype.clearTimer = function (handle) {
if (handle !== this.key)
return;
clearTimeout(this.timer);
this.timer = void 0;
this.currentTime = Infinity;
this.task = void 0;
};
VirtualTimer.prototype.tick = function (delay) {
if (delay <= 0)
return this.promise;
this.targetTime = this.targetTime + delay;
return this.run();
};
VirtualTimer.prototype.run = function () {
var _this = this;
if (this.running)
return this.promise;
this.running = true;
this.active = true;
return new Promise(function (resolve, reject) {
_this.timer = setTimeout(function () {
_this.step()
.then(function () { return resolve(); })
.catch(reject);
}, 0);
});
};
VirtualTimer.prototype.step = function () {
var _this = this;
return new Promise(function (resolve, reject) {
if (_this.time >= _this.targetTime) {
_this.time = _this.targetTime;
_this.currentTime = Infinity;
_this.running = false;
return resolve();
}
var task = _this.task;
_this.task = void 0;
_this.time = _this.currentTime;
_this.currentTime = Infinity;
if (typeof task === 'function')
task();
_this.timer = setTimeout(function () {
return _this.step()
.then(function () { return resolve(); })
.catch(reject);
}, 0);
});
};
return VirtualTimer;
}());
export { VirtualTimer };
//# sourceMappingURL=VirtualTimer.js.map