raf-timer
Version:
An abstraction around requestionAnimationFrame.
93 lines (76 loc) • 2.91 kB
JavaScript
;
var _createClass = function () { function defineProperties(target, props) { for (var i = 0; i < props.length; i++) { var descriptor = props[i]; descriptor.enumerable = descriptor.enumerable || false; descriptor.configurable = true; if ("value" in descriptor) descriptor.writable = true; Object.defineProperty(target, descriptor.key, descriptor); } } return function (Constructor, protoProps, staticProps) { if (protoProps) defineProperties(Constructor.prototype, protoProps); if (staticProps) defineProperties(Constructor, staticProps); return Constructor; }; }();
Object.defineProperty(exports, "__esModule", {
value: true
});
var _performance = require('./performance.now()-polyfill');
var _performance2 = _interopRequireDefault(_performance);
var _requestAnimationFramePolyfill = require('./requestAnimationFrame-polyfill');
function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; }
function _classCallCheck(instance, Constructor) { if (!(instance instanceof Constructor)) { throw new TypeError("Cannot call a class as a function"); } }
var numCallbacks = 0;
var callbackID = 0;
var animationFrameID = null;
var callbacks = {};
var runCallbacks = function runCallbacks(dt) {
animationFrameID = null;
for (var key in callbacks) {
callbacks[key](dt);
delete callbacks[key];
}
};
var Timer = function () {
function Timer() {
var deltaTimeLimit = arguments.length <= 0 || arguments[0] === undefined ? 0.25 : arguments[0];
_classCallCheck(this, Timer);
this.microTime = (0, _performance2.default)();
this.deltaTime = 0;
this.deltaTimeLimit = deltaTimeLimit;
this.animationFrameID = null;
}
_createClass(Timer, [{
key: 'cancelFrame',
value: function cancelFrame() {
delete callbacks[this.animationFrameID];
if (numCallbacks === 0) {
(0, _requestAnimationFramePolyfill.cancelAnimationFrame)(animationFrameID);
animationFrameID = null;
}
}
}, {
key: 'nextFrame',
value: function nextFrame(callback) {
var id = callbackID++;
numCallbacks++;
callbacks[id] = callback;
this.animationFrameID = id;
if (animationFrameID === null) {
animationFrameID = (0, _requestAnimationFramePolyfill.requestAnimationFrame)(runCallbacks);
}
}
}, {
key: 'step',
value: function step() {
var dt = (0, _performance2.default)() - this.microTime;
this.deltaTime = Math.max(0, Math.min(this.deltaTimeLimit, dt / 1000));
return this.microTime += dt;
}
}, {
key: 'delta',
get: function get() {
return this.deltaTime;
}
}, {
key: 'fps',
get: function get() {
return this.deltaTime === 0 ? 0 : 1 / this.deltaTime;
}
}, {
key: 'time',
get: function get() {
return this.microTime;
}
}]);
return Timer;
}();
exports.default = Timer;