CxJS

throttle

import { throttle } from 'cx/util'; Copied

throttle limits function execution to at most once per specified interval. Unlike debounce, it executes the function during ongoing calls rather than waiting for them to stop.

Signature

function throttle<T extends (...args: any[]) => void>(
  callback: T,
  delay: number
): T

Parameters

ParameterTypeDescription
callbackfunctionThe function to throttle.
delaynumberMinimum interval in milliseconds.

Return Value

Returns a throttled function that executes at most once per delay interval.

Examples

Basic usage

const log = throttle((message: string) => {
  console.log(message);
}, 1000);

// Called rapidly
log("1"); // executes immediately
log("2"); // ignored (within 1s)
log("3"); // ignored (within 1s)
// After 1 second, next call will execute
log("4"); // executes

Scroll handler

const handleScroll = throttle(() => {
  const scrollY = window.scrollY;
  updateHeader(scrollY);
}, 100);

window.addEventListener("scroll", handleScroll);

Mouse move handler

const handleMouseMove = throttle((e: MouseEvent) => {
  updateTooltipPosition(e.clientX, e.clientY);
}, 50);

element.addEventListener("mousemove", handleMouseMove);

Resize handler

const handleResize = throttle(() => {
  recalculateLayout();
}, 200);

window.addEventListener("resize", handleResize);

debounce vs throttle

ScenarioRecommended
Search as user typesdebounce
Window resizeEither
Scroll position trackingthrottle
Button click (prevent double)debounce
Mouse move trackingthrottle
Form auto-savedebounce

Visual comparison

Time:     0   100   200   300   400   500ms
Calls:    X X X X X X X X X X X X
Debounce:                         X (after calls stop)
Throttle: X         X         X     (periodic execution)

See Also