Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Scroll event firing too many times. I only want it to fire a maximum of, say, once per second

Tags:

javascript

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?

like image 702
Jonathan Ong Avatar asked Mar 08 '12 06:03

Jonathan Ong


2 Answers

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.

like image 151
nicholaides Avatar answered Sep 24 '22 19:09

nicholaides


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.

like image 35
jfriend00 Avatar answered Sep 22 '22 19:09

jfriend00