Skip to content

Instantly share code, notes, and snippets.

@getdave
Created May 13, 2017 14:28
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save getdave/e389ea72ddfc2eb716cbc1cc9af9e707 to your computer and use it in GitHub Desktop.
Save getdave/e389ea72ddfc2eb716cbc1cc9af9e707 to your computer and use it in GitHub Desktop.
Performant Handling of Scroll Events
var lastScrollY = 0;
var ticking = false;
var windowMiddle = $(window).height()/2;
var scrollCallback = function scrollCallback(e) {
var elementClosestToMiddle = _this.findElementClosestToMiddle(elements, {
windowMiddle: windowMiddle
});
// Update state
if (elementClosestToMiddle) {
store.setActiveElement( elementClosestToMiddle );
}
// allow further rAFs to be called
ticking = false;
};
var requestTick = function() {
if(!ticking) {
requestAnimationFrame(scrollCallback);
ticking = true;
}
}
$(window).on('scroll', function(e) {
lastScrollY = window.scrollY; // avoid "work" here
requestTick(); // defer work to rAF
});
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment