I've been running into some performance issues when a scroll event gets fired on a project i'm working on and found that debouncing the taxing stuff would be a viable solution:
jQuery(document).ready(function() {
jQuery(window).on('scroll', debounce(function(e) {
console.log('debounced');
console.log(e); // will print the corresponding jQuery object
// some heavy work
}, 250, true)
);
});
function debounce(func, wait, immediate) {
var timeout;
return function() {
var obj = this, args = arguments;
if (timeout) clearTimeout(timeout);
else if (immediate) func.apply(obj, args);
timeout = setTimeout(function() {
if (!immediate) func.apply(obj, args);
timeout = null;
}, wait || 100);
};
};
My question is, how come the jQuery event object is properly handed over within debounce() ? Isn't it supposed to be passed as first argument of function set as handler, here being debounce() ?
This solution seems to get the job done just fine, but is there some conceptual thing i'm missing here ?
NB: credits to John Hann for the debouncing function
debounceOnce()?