useInterval
HOOK

HOOKS & API / TIMERS

useInterval

Run a declarative interval callback on live desktop widgets with automatic cleanup and fresh closure state. Pass null to pause cleanly; paused automatically in preview mode.

Signature#

SIGNATURE
function useInterval(
  callback: () => void,
  delayMs: number | null
): void

Parameters#

callbackfunctionRequired
Zero-arg function () => void invoked on each tick; always sees fresh React state without stale closures.
delayMsnumber | nullRequired
Interval delay in milliseconds. Pass null to pause. Automatically paused when useWidget().isPreview === true.

Example: Pausable Pomodoro Timer#

TSX
import React, { Button, HStack, RingGauge, Spacer, VStack, useInterval, useState, useWidget } from "deskset-react";

const TOTAL_SECONDS = 25 * 60;

export default function FocusTimer() {
  const { theme, t, isPreview } = useWidget();
  const [remaining, setRemaining] = useState(isPreview ? 18 * 60 + 24 : TOTAL_SECONDS);
  const [running, setRunning] = useState(false);

  useInterval(() => {
    setRemaining((sec) => {
      if (sec <= 1) {
        setRunning(false);
        return 0;
      }
      return sec - 1;
    });
  }, running ? 1000 : null);

  const mins = String(Math.floor(remaining / 60)).padStart(2, "0");
  const secs = String(remaining % 60).padStart(2, "0");

  return (
    <VStack
      maxWidth={true}
      maxHeight={true}
      padding={14}
      spacing={10}
      alignment="center"
      background={theme.isPure ? "clear" : "theme.card"}
      cornerRadius={theme.isPure ? 0 : theme.corner}
      clip={!theme.isPure}
    >
      <RingGauge
        value={TOTAL_SECONDS - remaining}
        total={TOTAL_SECONDS}
        size={96}
        lineWidth={8}
        color="theme.accent"
        centerText={`${mins}:${secs}`}
        centerFontSize={18}
      />
      <Spacer />
      <HStack spacing={8}>
        <Button
          title={running ? t("暂停", "Pause") : t("开始", "Start")}
          variant="filled"
          color="theme.accent"
          onClick={() => setRunning((r) => !r)}
        />
        <Button
          icon="arrow.counterclockwise"
          variant="tinted"
          onClick={() => { setRunning(false); setRemaining(TOTAL_SECONDS); }}
        />
      </HStack>
    </VStack>
  );
}

Best Practices#

  • For clocks, prefer useHostData("clock", ...) — it aligns to wall-clock seconds and shares a single native timer across widgets.
  • For API polling, prefer useFetch(url, { refreshMs }) rather than combining useInterval and imperative fetch.
  • Keep intervals at >= 1000 ms whenever possible so desktop widgets stay near 0% idle CPU.