All files / src/hooks useCountdown.ts

31.57% Statements 6/19
0% Branches 0/8
33.33% Functions 1/3
31.57% Lines 6/19

Press n or j to go to the next uncovered block, b, p or k for the previous block.

1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49    116x             584x 584x 584x 584x                                                             584x          
import { useRef, useState } from "react";
 
const workerURL = new URL("./countdownWorker", import.meta.url);
 
export function useCountdown({
  onCountdownEnd,
}: {
  onCountdownEnd?: () => void;
}) {
  const [duration, setDuration] = useState(0);
  const [remainingTime, setRemainingTime] = useState<number>(0);
  const workerRef = useRef<Worker | null>(null);
  const startCountDown = ({
    duration,
    cb,
  }: {
    duration: number;
    cb?: () => void;
  }) => {
    // Terminate old worker if exists
    if (workerRef.current) {
      workerRef.current.terminate();
      workerRef.current = null;
    }
 
    // Create new worker
    workerRef.current = new Worker(workerURL, { type: "module" });
    workerRef.current.postMessage({ duration });
 
    //set the remaining time
    const onMessage = (event: MessageEvent) => {
      setRemainingTime(event.data);
      if (onCountdownEnd && event.data <= 0) {
        onCountdownEnd();
      }
    };
    workerRef.current.addEventListener("message", onMessage);
 
    setRemainingTime(duration);
    setDuration(duration);
    cb && cb();
  };
 
  return {
    timeLeft: remainingTime,
    startCountDown,
  };
}