debounce

debounce

The debounce function is commonly used to ensure that time-consuming tasks do not fire too often. It waits for a set interval after the last invocation before executing the callback function.

If immediate is set to true, the original function will be called immediately. However, the function won't be called again unless the debounced function stops being invoked for the specified duration.

Import

import { debounce } from '@fullstacksjs/toolbox';

Signature

function debounce<F>(
  options: { delay: number; immediate?: boolean },
  cb: F,
): (...args: Parameters<F>) => void {}

Examples

function log(id: number) {
  console.log(id);
}
 
const debounced = debounce({ delay: 1000 }, log);
 
debounced(1); // ignored
debounced(2); // ignored
debounced(3); // ignored
 
setTimeout(function () {
  debounced(4); // 4
  debounced(5); // ignored
}, 1000);
 
const debounced = debounce({ delay: 1000, immediate: true }, log);
 
debounced(1); // 1
debounced(2); // ignored
debounced(3); // ignored
 
setTimeout(function () {
  debounced(4); // 4
  debounced(5); // ignored
}, 1000);