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.
source share