phaser/src/dom/RequestAnimationFrame.js

89 lines
2 KiB
JavaScript
Raw Normal View History

var NOOP = require('../utils/NOOP');
// Abstracts away the use of RAF or setTimeOut for the core game update loop.
var RequestAnimationFrame = function ()
2016-11-25 00:34:37 +00:00
{
// @property {boolean} isRunning - true if RequestAnimationFrame is running, otherwise false.
2016-11-25 00:34:37 +00:00
this.isRunning = false;
this.callback = NOOP;
this.tick = 0;
// @property {boolean} isSetTimeOut - True if the browser is using setTimeout instead of rAf.
2016-11-25 00:34:37 +00:00
this.isSetTimeOut = false;
// @property {number} timeOutID - The callback setTimeout or rAf callback ID used when calling cancel.
2016-11-25 00:34:37 +00:00
this.timeOutID = null;
var _this = this;
2016-11-25 00:34:37 +00:00
// timestamp = DOMHighResTimeStamp
var step = function (timestamp)
2016-11-25 00:34:37 +00:00
{
_this.tick = timestamp;
2016-11-25 00:34:37 +00:00
_this.callback(timestamp);
2017-04-28 02:13:32 +00:00
_this.timeOutID = window.requestAnimationFrame(step);
2016-11-25 00:34:37 +00:00
};
var stepTimeout = function ()
2016-11-25 00:34:37 +00:00
{
var d = Date.now();
_this.tick = d;
_this.callback(d);
2017-04-28 02:13:32 +00:00
_this.timeOutID = window.setTimeout(stepTimeout, _this.timeToCall);
2016-11-25 00:34:37 +00:00
};
this.step = step;
this.stepTimeout = stepTimeout;
};
RequestAnimationFrame.prototype.constructor = RequestAnimationFrame;
RequestAnimationFrame.prototype = {
// Starts the requestAnimationFrame running or setTimeout if unavailable in browser
start: function (callback, forceSetTimeOut)
2016-11-25 00:34:37 +00:00
{
this.callback = callback;
2016-11-25 00:34:37 +00:00
this.isSetTimeOut = forceSetTimeOut;
2016-11-25 00:34:37 +00:00
this.isRunning = true;
2016-11-25 00:34:37 +00:00
var _this = this;
this.timeOutID = (forceSetTimeOut) ? window.setTimeout(_this.stepTimeout, 0) : window.requestAnimationFrame(_this.step);
},
2016-11-25 00:34:37 +00:00
// Stops the requestAnimationFrame from running.
stop: function ()
2016-11-25 00:34:37 +00:00
{
this.isRunning = false;
if (this.isSetTimeOut)
{
clearTimeout(this.timeOutID);
}
else
{
window.cancelAnimationFrame(this.timeOutID);
}
},
2016-11-25 00:34:37 +00:00
destroy: function ()
2016-11-25 00:34:37 +00:00
{
this.stop();
this.callback = NOOP;
}
2016-11-25 00:34:37 +00:00
};
2016-11-25 00:34:37 +00:00
module.exports = RequestAnimationFrame;