fn

useThrottleFn

v0.0.14testeddemo

Throttle execution of a function — a thin reactive wrapper around @robonen/stdlib's throttle. Invokes fn at most once per delay window and resolves with the wrapped function's result. Especially useful for rate-limiting handlers on high-frequency events like scroll and resize. Accepts either positional arguments or a single options object, and exposes cancel/flush controls on the returned function.

Examples

ts
const onScroll = useThrottleFn(() => updatePosition(), 100);
useEventListener('scroll', onScroll);
ts
const save = useThrottleFn(persist, { delay: 1000, trailing: true });
save.cancel();

Demo

Loading demo…

Signatures

ts
export function useThrottleFn<T extends AnyFunction>(
  fn: T,
  options: UseThrottleFnOptions,
): UseThrottleFnReturn<T>;
ts
export function useThrottleFn<T extends AnyFunction>(
  fn: T,
  ms?: MaybeRefOrGetter<number>,
  trailing?: boolean,
  leading?: boolean,
  rejectOnCancel?: boolean,
): UseThrottleFnReturn<T>;

Type Parameters

Textends AnyFunction

Parameters

ParameterTypeDescription
fnTThe function to throttle
ms?MaybeRefOrGetter<number> | UseThrottleFnOptionsWindow in milliseconds (can be reactive) or an options object
trailing?booleanInvoke on the trailing edge of the window
leading?booleanInvoke on the leading edge of the window
rejectOnCancel?booleanReject a superseded/cancelled trailing promise instead of resolving it

Returns

UseThrottleFnReturn<T>The throttled function with cancel and flush