aboutsummaryrefslogtreecommitdiffstats
path: root/src/app/use_timer.ts
blob: 487591df658d23d1d0bcede7c579d4fe841e711c (plain) (blame)
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
import { useEffect, useState, useCallback } from "react";

function useTimer(speed = 1) {
  const [paused, setPaused] = useState(true);
  const play = useCallback(() => setPaused(false), []);
  const pause = useCallback(() => setPaused(true), []);

  const [currentMillisecond, setCurrentMillisecond] = useState(0);
  const reset = useCallback(() => setCurrentMillisecond(0), []);

  useEffect(() => {
    if (!paused) {
      let last = Date.now();
      const timer = window.setInterval(() => {
        const now = Date.now();
        setCurrentMillisecond((cm) => cm + (now - last) * speed);
        last = now;
      }, 97);
      return () => window.clearInterval(timer);
    }
  }, [paused, speed]);

  return {
    currentMillisecond,
    setCurrentMillisecond,
    reset,
    paused,
    play,
    pause
  };
}

export default useTimer;
send patches to the email below
yukais@pinapelz.com
include the subject [PATCH repo_name]
pinapelz.com
homepage