- Throttle — run at most once per interval while events keep coming. Use for scroll and resize handlers, drag, progress bars.
- Debounce — run once, after events stop for the interval. Use for search-as-you-type, autosave, validation.
Both return a new function that preserves this and arguments, so they drop straight into .on(). For declarative requests, kj-trigger="keyup delay:300ms" debounces without any JavaScript.
View the source for this demo
<div id="dt-pad" class="dt-pad" tabindex="0" aria-label="Event pad: move the pointer here, or focus it and hold any key">Move your pointer here — or focus and hold a key</div>
<div class="dt-lanes">
<div class="dt-lane"><span>raw events</span><div id="lane-raw"></div><b id="n-raw">0</b></div>
<div class="dt-lane"><span>throttle 200ms</span><div id="lane-thr"></div><b id="n-thr">0</b></div>
<div class="dt-lane"><span>debounce 300ms</span><div id="lane-deb"></div><b id="n-deb">0</b></div>
</div>const WINDOW = 4000;
let t0 = performance.now();
const counts = { raw: 0, thr: 0, deb: 0 };
function tick(lane) {
const now = performance.now();
if (now - t0 > WINDOW) { t0 = now; $('.dt-lane > div').empty(); } // start a new 4 s window
counts[lane]++;
$('#n-' + lane).text(counts[lane]);
$('<i>').css('left', ((now - t0) / WINDOW * 100).toFixed(2) + '%').appendTo('#lane-' + lane);
}
const throttled = $.throttle(() => tick('thr'), 200);
const debounced = $.debounce(() => tick('deb'), 300);
$('#dt-pad').on('pointermove keydown', () => { tick('raw'); throttled(); debounced(); });More examples
Typical uses
$(window).on('scroll', $.throttle(updateProgressBar, 50));
$('#search').on('input', $.debounce(function () { search(this.value); }, 300));
$(window).on('resize', $.debounce(relayout, 150));API
Returns a function that fires only after calls stop for wait ms.
Returns a function that fires at most once per wait ms.
Related features
Triggers & debouncing
Choose when requests fire with kj-trigger: any DOM event plus a debounce like keyup delay:400ms — live search and server-side inline validation without JavaScript..
Open →CoreGeometry, scroll & visibility
Measure and position elements with width(), height(), offset() and position(), control scrolling with scrollTop(), and show or hide elements without losing their display value..
Open →UtilitiesUtilities
The $ helper belt: $.each, $.map, $.extend (deep, prototype-pollution safe), $.param, $.parseHTML, $.escape, $.uuid, type checks and $.noConflict — run them live..
Open →