I have a page with "infinite scroll". It calculates the difference between the end of the page and the current page and loads more content if this difference is small enough. The code is soemthing like this using jQuery:
$(window).on('scroll', function() { if (window.pageYOffset > loadMoreButton.offsetTop - 1000) # load more content via ajax }
Now, the problem is that every time I scroll, this event fires multiple times per scroll. I would like fire at most every x milliseconds. How would I do this?
Check out the Underscore.js library's "throttle" method.
http://underscorejs.org/#throttle
The example it gives is exactly what you're asking about - limiting how often you have to handle scroll events.
One way to solve this problem is to define a time interval and only process a scroll event once within that time interval. If more than one scroll event comes in during that time interval, you ignore it and process it only when that time interval has passed.
var scrollTimer, lastScrollFireTime = 0; $(window).on('scroll', function() { var minScrollTime = 100; var now = new Date().getTime(); function processScroll() { console.log(new Date().getTime().toString()); } if (!scrollTimer) { if (now - lastScrollFireTime > (3 * minScrollTime)) { processScroll(); // fire immediately on first scroll lastScrollFireTime = now; } scrollTimer = setTimeout(function() { scrollTimer = null; lastScrollFireTime = new Date().getTime(); processScroll(); }, minScrollTime); } });
This will fire the first scroll event immediately and then get you a scroll event approximately once every 100ms while the scrollbar is being moved and then one final event after the scrollbar stops moving. You can adjust the frequency of the event by changing the argument to the setTimeout
(what is currently set to 100).
There is a demo here: http://jsfiddle.net/jfriend00/EBEqZ/ which you need to open a debug console window, start moving the scrollbar in the content window and then watch the time of each scroll event in the debug console window. On my version of Chrome, they are set for a minimum spacing of 100ms and they seem to occur every 100-200ms.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With