Skip to content

Instantly share code, notes, and snippets.

@sethblanchard
Created December 4, 2015 16:10
Show Gist options
  • Save sethblanchard/2fe8ceca43329811dbf2 to your computer and use it in GitHub Desktop.
Save sethblanchard/2fe8ceca43329811dbf2 to your computer and use it in GitHub Desktop.
(function() {
var lastTime = 0;
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'];
}
if (!window.requestAnimationFrame)
window.requestAnimationFrame = function(callback, element) {
var currTime = new Date().getTime();
var timeToCall = Math.max(0, 16 - (currTime - lastTime));
var id = window.setTimeout(function() { callback(currTime + timeToCall); },
timeToCall);
lastTime = currTime + timeToCall;
return id;
};
if (!window.cancelAnimationFrame)
window.cancelAnimationFrame = function(id) {
clearTimeout(id);
};
}());
var lastScrollY = 0,
ticking = false;
function onScroll() {
lastScrollY = $(window).scrollTop();
requestTick();
}
/**
* Calls rAF if it's not already
* been done already
*/
function requestTick() {
if(!ticking) { //Figure out someway to queue setTimeout callback fixes
requestAnimationFrame(batchScrollActions);
ticking = true;
}
}
var batchScrollActions = function(){
/*******
* Do your expensive thing here!
***/
ticking = false;
};
window.addEventListener('scroll', onScroll, false);
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment