narinder1231 commited on
Commit
9b0016a
·
1 Parent(s): 73a2501

Add useTimer hook for managing a timer with start, stop, and formatting functionality

Browse files
Files changed (1) hide show
  1. src/hooks/useTimer.ts +29 -0
src/hooks/useTimer.ts ADDED
@@ -0,0 +1,29 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ import { useState, useRef } from "react";
2
+
3
+ export function useTimer() {
4
+ const [seconds, setSeconds] = useState(0);
5
+ const intervalRef = useRef<ReturnType<typeof setInterval> | null>(null);
6
+
7
+ function startTimer() {
8
+ setSeconds(0);
9
+ intervalRef.current = setInterval(() => {
10
+ setSeconds((prev) => prev + 1);
11
+ }, 1000);
12
+ }
13
+
14
+ function stopTimer() {
15
+ if (intervalRef.current) {
16
+ clearInterval(intervalRef.current);
17
+ }
18
+ setSeconds(0);
19
+ }
20
+
21
+ function formatTime(seconds: number) {
22
+ const hrs = Math.floor(seconds / 3600);
23
+ const mins = Math.floor((seconds % 3600) / 60);
24
+ const secs = seconds % 60;
25
+ return `${String(hrs).padStart(2, "0")}:${String(mins).padStart(2, "0")}:${String(secs).padStart(2, "0")}`;
26
+ }
27
+
28
+ return { timer: formatTime(seconds), startTimer, stopTimer };
29
+ }