Skip to content

Instantly share code, notes, and snippets.

@Troland
Created June 25, 2018 15:52
Show Gist options
  • Save Troland/7044c169d8a34ad52a13e8a353ac173d to your computer and use it in GitHub Desktop.
Save Troland/7044c169d8a34ad52a13e8a353ac173d to your computer and use it in GitHub Desktop.
Reduce unnessary frame loss and ensure every module init when the browser is idle.
(function() {
let lastTime = 0;
const vendors = ['ms', 'moz', 'webkit', 'o'];
for(let x = 0; x < vendors.length && !window.requestAnimationFrame; ++x) {
window.requestAnimationFrame = window[vendors[x]+'RequestAnimationFrame'];
window.cancelAnimationFrame = window[vendors[x]+'CancelAnimationFrame'] || window[vendors[x]+'CancelRequestAnimationFrame'];
}
if (!window.requestAnimationFrame) {
window.requestAnimationFrame = (callback, element) => {
var currTime = new Date().getTime();
var timeToCall = Math.max(0, 16 - (currTime - lastTime));
var id = window.setTimeout(() => { callback(currTime + timeToCall); }, timeToCall);
lastTime = currTime + timeToCall;
return id;
};
}
if (!window.cancelAnimationFrame) {
window.cancelAnimationFrame = (id) => {
clearTimeout(id);
};
}
})();
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment