Skip to content

Function Utilities

Function helpers. Currently ships one: debounce.

import { debounce } from '@msflib/typescript';

debounce

debounce<T extends (...args: any[]) => void>(
  fn: T,
  delay: number, // milliseconds
): (...args: Parameters<T>) => void;

Returns a wrapped function that postpones calling fn until delay ms have passed since the last call. Only the arguments of the last call are used (trailing edge only).

import { debounce } from '@msflib/typescript';

const log = (msg: string) => console.log(msg);
const debouncedLog = debounce(log, 500);

debouncedLog('Hello');
debouncedLog('World');
// Only "World" will be logged after 500ms

Typical use - searching as the user types:

const search = debounce((term: string) => {
  apiClient('GET', '/search', null, { query: { q: term } }).then(render);
}, 300);

input.addEventListener('input', (e) => search((e.target as HTMLInputElement).value));

Contract

  • The wrapper returns void - fn's return value is discarded, so it is not suitable for debouncing a function whose result you need.
  • There is no cancel() or flush(). A pending call still fires after a component unmounts; guard inside fn if that matters.
  • In React, create the debounced function once (e.g. with useMemo/useRef), not on every render, or each render gets its own timer.

See also: Object utilities ยท String utilities