Skip to main content

useTimerGroup

import { useTimerGroup } from '@crup/react-timer-hook/group';

function useTimerGroup(options?: UseTimerGroupOptions): TimerGroupResult;

Use useTimerGroup() when every row needs independent pause, resume, cancel, restart, schedules, or onEnd.

Item schedules use the same TimerSchedule contract as useScheduledTimer(), including the third schedule context argument for intended fire time, actual fire time, next run time, and overdue interval count.

type UseTimerGroupOptions = {
updateIntervalMs?: number;
items?: TimerGroupItem[];
diagnostics?: TimerDiagnostics;
};

type TimerGroupItem = {
id: string;
autoStart?: boolean;
endWhen?: (snapshot: TimerSnapshot) => boolean;
onEnd?: (snapshot: TimerSnapshot, controls: TimerGroupItemControls) => void | Promise<void>;
onError?: (error: unknown, snapshot: TimerSnapshot, controls: TimerGroupItemControls) => void;
schedules?: TimerSchedule[];
};

onError receives sync throws and async rejections from that item's onEnd. It also handles item schedule callback failures when a schedule does not define its own onError.

When items is controlled by props, pass a new array/object when item definitions change. The store preserves state for existing IDs and syncs new callbacks, deadlines, and schedules without resetting the item generation.

Result

type TimerGroupResult = {
now: number;
size: number;
ids: string[];
get(id: string): TimerSnapshot | undefined;
add(item: TimerGroupItem): void;
update(id: string, item: Partial<Omit<TimerGroupItem, 'id'>>): void;
remove(id: string): void;
clear(): void;
start(id: string): void;
pause(id: string): void;
resume(id: string): void;
reset(id: string, options?: { autoStart?: boolean }): void;
restart(id: string): void;
cancel(id: string, reason?: string): void;
startAll(): void;
pauseAll(): void;
resumeAll(): void;
resetAll(options?: { autoStart?: boolean }): void;
restartAll(): void;
cancelAll(reason?: string): void;
};