Skip to content
Gallery

JavaScript

Debounce a callback

19 lines 1 view by Md Shamim Hossain · published 26 Oct 2026

The helper that stops a search field firing on every keystroke. It logs on each call and again when the typing settles, so the difference between the two is visible in the console pane.

.js

function debounce(fn, wait = 300) {
  let timer;

  return (...args) => {
    clearTimeout(timer);
    timer = setTimeout(() => fn(...args), wait);
  };
}

const onSettled = debounce((value) => {
  console.log('search fired for', value);
}, 400);

for (const keystroke of ['la', 'lar', 'lara', 'larav']) {
  console.log('keystroke', keystroke);
  onSettled(keystroke);
}

console.warn('only the last keystroke should reach the search');
Run this in a sandbox This is somebody else’s code. The frame it runs in has no access to this site, your session, or this page, and nothing happens until you press the button. It can still loop, so Stop replaces it.
Preview allow-scripts only
Console

Nothing logged yet. console.log, console.warn and uncaught errors from the frame arrive here. alert() is blocked and says so.

Enter your credentials to continue to your workspace.
Email address
Remember me
Don't have an account? Sign up
Enter your details below to create your account
Name
Email address
Password
Confirm password
Already have an account? Log in
Enter your email and we will send you a reset link
Email address
Or, return to log in