Hooks

useThrottle

Cap how often a callback runs - at most once per delayms with leading and trailing invocation. The companion to useDebounce: debounce waits for a pause in calls; throttle guarantees a steady maximum rate. Ideal for scroll, resize, mousemove, and drag handlers. Any pending timer is cleared on teardown.

Mousemove throttle

Move the mouse over the area below. The coordinates update at most every 50ms - without throttle every pixel movement would trigger a re-render.

Move mouse here: 0, 0
<script lang="ts">
  import { useThrottle } from 'sv5ui';

  let x = $state(0);
  let y = $state(0);
  const throttle = useThrottle({ delay: 50 });

  function onMouseMove(e: MouseEvent) {
    throttle.run(() => {
      x = e.clientX;
      y = e.clientY;
    });
  }
</script>

<div onmousemove={onMouseMove} class="h-32 rounded border flex items-center justify-center">
  Move mouse: {x}, {y}
</div>

Cancel trailing call

Click rapidly - the counter only increments on the leading edge and once more after the cooldown. Use cancel() to discard the pending trailing call. Check throttle.pending to know if one is queued.

Count: 0
<script lang="ts">
  import { useThrottle, Badge } from 'sv5ui';

  let count = $state(0);
  const throttle = useThrottle({ delay: 500 });

  function onClick() {
    throttle.run(() => count++);
  }
</script>

<button onclick={onClick}>Click fast ({count})</button>
{#if throttle.pending}
  <Badge label="Trailing call pending..." variant="soft" color="warning" size="xs" />
{/if}
<button onclick={() => throttle.cancel()}>Cancel trailing</button>

Options

OptionTypeDefault
delaynumber200

Return

PropertyType-
pendingboolean-
run(callback: () => void) => void-
cancel() => void-