generated from muhtadeetaron/nextjs-template
49 lines
1.2 KiB
TypeScript
49 lines
1.2 KiB
TypeScript
"use client";
|
|
|
|
import { create } from "zustand";
|
|
|
|
interface TimerState {
|
|
timeRemaining: number;
|
|
timerRef: NodeJS.Timeout | null;
|
|
|
|
resetTimer: (duration: number, onComplete?: () => void) => void;
|
|
stopTimer: () => void;
|
|
setInitialTime: (duration: number) => void;
|
|
}
|
|
|
|
export const useTimerStore = create<TimerState>((set, get) => ({
|
|
timeRemaining: 0,
|
|
timerRef: null,
|
|
|
|
resetTimer: (duration, onComplete) => {
|
|
const { timerRef } = get();
|
|
|
|
if (timerRef) clearInterval(timerRef);
|
|
|
|
const newRef = setInterval(() => {
|
|
set((state) => {
|
|
if (state.timeRemaining <= 1) {
|
|
clearInterval(newRef);
|
|
if (onComplete) onComplete(); // ✅ call callback when timer ends
|
|
return { timeRemaining: 0, timerRef: null };
|
|
}
|
|
return { timeRemaining: state.timeRemaining - 1 };
|
|
});
|
|
}, 1000);
|
|
|
|
set({ timeRemaining: duration, timerRef: newRef });
|
|
},
|
|
|
|
stopTimer: () => {
|
|
const { timerRef } = get();
|
|
if (timerRef) clearInterval(timerRef);
|
|
set({ timeRemaining: 0, timerRef: null });
|
|
},
|
|
|
|
setInitialTime: (duration) => {
|
|
const { timerRef } = get();
|
|
if (timerRef) clearInterval(timerRef);
|
|
set({ timeRemaining: duration, timerRef: null });
|
|
},
|
|
}));
|