Skip to content

Instantly share code, notes, and snippets.

@julienetie
Created July 28, 2015 01:16
Show Gist options
  • Select an option

  • Save julienetie/c29fb7b7e4387c4df00c to your computer and use it in GitHub Desktop.

Select an option

Save julienetie/c29fb7b7e4387c4df00c to your computer and use it in GitHub Desktop.
Sets the frame rate of requestAnimationFrame in FPS without setTimeout/ setInterval, performance or Date functions. Works for all browsers
// new Date().getTime() is only used to set inital time once for outdated browsers.
/**
* setFPS sets the frame rate of the rAF function
* with minimum overhead.
* @Copyright Julien Etienne 2015
* @License MIT
*/
function setFPS(callback, rAF, fps) {
// indexOf polyfill from MDN
if (!Array.prototype.indexOf) {
Array.prototype.indexOf = function(searchElement, fromIndex) {
var k;
if (this == null) {
throw new TypeError('"this" is null or not defined');
}
var O = Object(this);
var len = O.length >>> 0;
if (len === 0) {
return -1;
}
var n = +fromIndex || 0;
if (Math.abs(n) === Infinity) {
n = 0;
}
if (n >= len) {
return -1;
}
k = Math.max(n >= 0 ? n : len - Math.abs(n), 0);
while (k < len) {
if (k in O && O[k] === searchElement) {
return k;
}
k++;
}
return -1;
};
}
function isAnimationFrameFunction(func) {
if (!func) {
return;
}
var reference = func.toString();
reference = reference.indexOf('AnimationFrame') > -1;
return reference;
}
if (isAnimationFrameFunction(rAF)) {
this.fPSTimeStamp = 0;
} else {
this.fPSTimeStamp = new Date().getTime();
}
(function loopCallback(time) {
if (time > fPSTimeStamp) {
fPSTimeStamp += 1000 / fps;
callback();
}
rAF(loopCallback);
}());
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment