Created
May 13, 2017 14:28
-
-
Save getdave/e389ea72ddfc2eb716cbc1cc9af9e707 to your computer and use it in GitHub Desktop.
Performant Handling of Scroll Events
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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