Debounce and throttle helpers
Debounce waits until the events stop. Throttle runs at most once per interval.
jQuery · Debounce and throttle helpersAdvanced
$.debounce = function (fn, wait) {
let t;
return function () {
const ctx = this, args = arguments;
clearTimeout(t);
t = setTimeout(function () { fn.apply(ctx, args); }, wait);
};
};
$.throttle = function (fn, limit) {
let last = 0;
return function () {
const now = Date.now();
if (now - last >= limit) { last = now; fn.apply(this, arguments); }
};
};
$(window).on('resize', $.debounce(function () { console.log('resize finished'); }, 200));
$(window).on('scroll', $.throttle(function () { console.log('scrolling'); }, 100));debouncethrottlescrollresizeperformance