Utilities

Debounce & throttle

Move your pointer over the pad. Raw events flood in; $.throttle() lets one through every 200 ms; $.debounce() waits until you stop.

  • 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.

Live · Event lanes (4-second window)

Move your pointer here — or focus and hold a key
raw events
0
throttle 200ms
0
debounce 300ms
0
View the source for this demo
HTML
<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>
JavaScript
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

JavaScript
$(window).on('scroll', $.throttle(updateProgressBar, 50));
$('#search').on('input', $.debounce(function () { search(this.value); }, 300));
$(window).on('resize', $.debounce(relayout, 150));

API

$.debounce(fn [, wait = 300]) → fn

Returns a function that fires only after calls stop for wait ms.

Reference: $.debounce() →
$.throttle(fn [, wait = 300]) → fn

Returns a function that fires at most once per wait ms.

Reference: $.throttle() →

Related features