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.