UNPKG

raf-engine

Version:
78 lines (77 loc) 2.67 kB
"use strict"; Object.defineProperty(exports, "__esModule", { value: true }); ; var RAFEngine = /** @class */ (function () { function RAFEngine() { var _this = this; this.lastRAFId = 0; this.frameId = 0; this.lastNow = 0; this.uidCounter = 0; this.stopped = true; this.queue = []; if (typeof window === 'undefined' || typeof window.requestAnimationFrame === 'undefined') { throw new Error("You are not using this package in browser environment"); } this.frameHandler = function () { return _this.frame(); }; } RAFEngine.prototype.start = function () { this.stopped = false; this.lastNow = performance.now(); this.lastRAFId = window.requestAnimationFrame(this.frameHandler); }; RAFEngine.prototype.stop = function (force) { if (force === void 0) { force = false; } if (force) { window.cancelAnimationFrame(this.lastRAFId); } this.stopped = true; }; RAFEngine.prototype.frame = function () { var _this = this; // Get the distance between this execution and the last var now = performance.now(); var delta = now - this.lastNow; this.lastNow = now; // Process the que for this frame this.queue.forEach(function (fn) { if (!fn.isHeavy) { fn.handler(delta, _this.frameId); } else if (_this.frameId % 2 === 0) { fn.handler(delta, _this.frameId); } }); this.frameId += 1; // Continus the loop if not already stopped if (!this.stopped) { this.lastRAFId = window.requestAnimationFrame(this.frameHandler); } }; RAFEngine.prototype.add = function (handler, id, isHeavy) { if (isHeavy === void 0) { isHeavy = false; } if (typeof handler !== 'function') throw new Error("Expected function as handler"); if (typeof id === 'undefined') id = "h_" + ++this.uidCounter; this.queue.push({ id: id, handler: handler, isHeavy: isHeavy, }); return id; }; RAFEngine.prototype.remove = function (id) { if (typeof id === 'undefined') throw new Error("Expected id"); var index = this.queue.findIndex(function (object) { return object.id === id; }); if (index < 0) return; else this.queue.splice(index, 1); if (this.queue.length <= 0) this.stop(); }; return RAFEngine; }()); exports.default = RAFEngine;