How to reduce the number of triggered mouse scroll events in a time interval to one event

Currently, on my site, I have a mousewheel function that scrolls the user to set positions on the page. This function, however, is triggered several times when users scroll somewhat quickly and do not limit their scrolling to a single mouse scroll unit. How can I take all mouse scroll events for a specific time interval, say one second, and make it a trigger for my function at a time?

+4
source share
2 answers

You can use debouncing for your event handler. Underscore / lodash provide debounce functionality, but jQuery does not. A simple example taken from here is as follows:

function debounce(func, wait, immediate) { var timeout; return function() { var context = this, args = arguments; var later = function() { timeout = null; if (!immediate) func.apply(context, args); }; var callNow = immediate && !timeout; clearTimeout(timeout); timeout = setTimeout(later, wait); if (callNow) func.apply(context, args); }; }; 

Once you have this, you can use it as follows:

 var delay = 1000; // 1s var handlerFunction = debounce(function (e) { console.log(1); }, delay); $(document).on('scroll', handlerFunction); 

And your handler will only execute 1000 ms after the last handler call.

JSBIN is here for you.

+3
source

This jQuery code allows you to set the interval in milliseconds.

 var intervalMs = 2000; var last = 0; $(document).scroll(function() { var now = new Date().getTime(); if (last + intervalMs < now) { last = now; // do stuff } }); 
0
source

All Articles