UNPKG

@smoud/tiny

Version:

Fast and tiny JavaScript library for HTML5 game and playable ads creation.

105 lines (77 loc) 2.62 kB
var _isSetTimeOut, _onLoop, _timeOutID, _prevTime, _lastTime; var now = function () { return new Date().getTime(); }; if (self.performance !== undefined && self.performance.now !== undefined) { now = self.performance.now.bind(self.performance); } else if (Date.now !== undefined) { now = Date.now; } var RAF = function (game, forceSetTimeOut) { if (forceSetTimeOut === undefined) { forceSetTimeOut = false; } this.game = game; this.isRunning = false; this.forceSetTimeOut = forceSetTimeOut; var vendors = ['ms', 'moz', 'webkit', 'o']; for (var x = 0; x < vendors.length && !window.requestAnimationFrame; x++) { window.requestAnimationFrame = window[vendors[x] + 'RequestAnimationFrame']; window.cancelAnimationFrame = window[vendors[x] + 'CancelAnimationFrame'] || window[vendors[x] + 'CancelRequestAnimationFrame']; } _isSetTimeOut = false; _onLoop = null; _timeOutID = null; _prevTime = 0; _lastTime = 0; }; RAF.prototype = { start: function () { _prevTime = now(); this.isRunning = true; var _this = this; if (!window.requestAnimationFrame || this.forceSetTimeOut) { _isSetTimeOut = true; _onLoop = function () { return _this.updateSetTimeout(); }; _timeOutID = window.setTimeout(_onLoop, 0); } else { _isSetTimeOut = false; _onLoop = function () { return _this.updateRAF(); }; _timeOutID = window.requestAnimationFrame(_onLoop); } }, updateRAF: function () { _lastTime = now(); if (this.isRunning) { this.game._update(Math.floor(_lastTime), _lastTime - _prevTime); _timeOutID = window.requestAnimationFrame(_onLoop); } _prevTime = _lastTime; }, updateSetTimeout: function () { _lastTime = now(); if (this.isRunning) { this.game._update(Math.floor(_lastTime), _lastTime - _prevTime); _timeOutID = window.setTimeout(_onLoop, RAF.timeToCall); } _prevTime = _lastTime; }, reset: function () { _prevTime = now(); }, stop: function () { if (_isSetTimeOut) { clearTimeout(_timeOutID); } else { window.cancelAnimationFrame(_timeOutID); } this.isRunning = false; } }; RAF.timeToCall = 15; export { RAF };