Hooks

useInterval

Run a callback on a repeating interval with proper runes teardown. The delay may be a reactive getter - changing it restarts the interval with the new period. Pass null to disable it entirely. Returns pause and resume for imperative control. SSR-safe - no timer runs on the server.

Pause & resume

Use the returned pause / resume methods and read timer.active reactively.

Count: 0 ● running

<script lang="ts">
  import { useInterval } from 'sv5ui';

  let count = $state(0);
  const timer = useInterval(() => count++, 1000);
</script>

<p>Count: {count} - {timer.active ? 'running' : 'paused'}</p>
<button onclick={timer.pause}>Pause</button>
<button onclick={timer.resume}>Resume</button>

Reactive delay

Pass a getter () => speed - whenever speed changes the interval restarts at the new period.

every 500ms

Ticks: 0

<script lang="ts">
  import { useInterval } from 'sv5ui';

  let speed = $state(500);
  let ticks = $state(0);

  // Changing speed restarts the interval with the new period
  useInterval(() => ticks++, () => speed);
</script>

<input type="range" min="200" max="2000" step="200" bind:value={speed} />
<p>Tick every {speed}ms - total: {ticks}</p>

Disable with null

Return null from the delay getter to disable the interval entirely without unmounting the component.

Count: 0

<script lang="ts">
  import { useInterval } from 'sv5ui';

  let enabled = $state(true);
  let count = $state(0);

  // Pass null to disable the interval entirely
  useInterval(() => count++, () => enabled ? 1000 : null);
</script>

<button onclick={() => (enabled = !enabled)}>
  {enabled ? 'Disable' : 'Enable'} interval
</button>
<p>Count: {count}</p>

Parameters

ParameterTypeDefault
callback() => void-
delaynumber | null | (() => number | null)-

Options

OptionTypeDefault
pausedboolean | (() => boolean)false

Return

PropertyType-
activeboolean-
pause() => void-
resume() => void-