File size: 1,538 Bytes
a0fda44
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
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
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
import { useState, useMemo, useEffect } from "react";

const useCounter = ({ showCentiseconds }) => {
  //   Time counter, updates every second
  const [counter, setCounter] = useState(0);

  // Counter pause/play
  const [played, setPlayed] = useState();

  //   Time interveal function, in order to be cleared on stopping recording
  const [timingInterval, setTimingInterval] = useState(null);

  useEffect(() => {
    if (!played) clearInterval(timingInterval);
    else {
      startCounter();
    }
  }, [played]);

  //   Format duration into centiseconds
  const formattedTime = useMemo(() => {
    // 6000 centiseconds make a minute
    const minutesSpent = String(Math.floor(counter / 6000));
    const secondsSpent = String(
      Math.floor((counter - minutesSpent * 6000) / 100)
    ).padStart(2, "0");
    const centiseconds = String(counter % 100).padStart(2, "0");

    return `${minutesSpent}:${secondsSpent}${
      showCentiseconds ? `,${centiseconds}` : ""
    }`;
  }, [counter]);

  // Start counter
  const startCounter = () => {
    setTimingInterval(
      setInterval(() => {
        setCounter((prevState) => prevState + 1);
      }, 10)
    );
  };

  // Stop counter
  const stopCounter = () => {
    clearInterval(timingInterval);
    setCounter(0);
    setTimingInterval(null);
    setPlayed();
  };

  // Pause and play counter
  const playCounter = (mode) => {
    setPlayed(mode);
  };

  return {
    formattedTime,
    startCounter,
    stopCounter,
    playCounter,
  };
};

export default useCounter;