Util

throttle

Wrap a callback so it fires at most every waitMs, honouring both the leading and trailing edge. Returns a function with a .cancel() method for safe teardown.

Usage

import { throttle } from 'ngwr/utils';

const onScroll = throttle(() => trackScroll(), 100);
window.addEventListener('scroll', onScroll);

onScroll.cancel();   // teardown

Why ngwr provides this

Hand-rolled throttles almost always forget the trailing edge — so the final scroll position / drag coordinate is silently dropped. ngwr's version handles both edges and exposes .cancel() so component teardown stays clean.

// Native — most hand-rolled throttles forget the trailing edge.
let lastRun = 0;
function onScroll() {
  const now = Date.now();
  if (now - lastRun >= 100) {
    lastRun = now;
    trackScroll();
  }
}
// → final scroll position is never reported (no trailing call).

// ngwr — leading + trailing edge, with `.cancel()` for teardown.
const onScroll = throttle(() => trackScroll(), 100);
destroyRef.onDestroy(() => onScroll.cancel());

API

NameDescriptionTypeDefault
throttle(fn, waitMs)Returns a wrapper that fires fn at most every waitMs (leading and trailing edge). Exposes .cancel() for teardown.(fn, ms) => WrThrottledFn