駅名標の動作が不完全だった問題を修正
This commit is contained in:
45
lib/useInterval.js
Normal file
45
lib/useInterval.js
Normal file
@@ -0,0 +1,45 @@
|
||||
import { useEffect, useRef, useState } from "react";
|
||||
|
||||
// type Control = {
|
||||
// start: () => void;
|
||||
// stop: () => void;
|
||||
// };
|
||||
|
||||
// type State = 'RUNNING' | 'STOPPED';
|
||||
|
||||
// type Fn = () => void;
|
||||
|
||||
export const useInterval = (fn, interval, autostart = true) => {
|
||||
const onUpdateRef = useRef();
|
||||
const [state, setState] = useState("RUNNING");
|
||||
const start = () => {
|
||||
setState("RUNNING");
|
||||
};
|
||||
const stop = () => {
|
||||
setState("STOPPED");
|
||||
};
|
||||
useEffect(() => {
|
||||
onUpdateRef.current = fn;
|
||||
}, [fn]);
|
||||
useEffect(() => {
|
||||
if (autostart) {
|
||||
setState("RUNNING");
|
||||
}
|
||||
}, [autostart]);
|
||||
useEffect(() => {
|
||||
let timerId;
|
||||
if (state === "RUNNING") {
|
||||
timerId = setInterval(() => {
|
||||
onUpdateRef.current?.();
|
||||
}, interval);
|
||||
} else {
|
||||
timerId && clearInterval(timerId);
|
||||
}
|
||||
return () => {
|
||||
timerId && clearInterval(timerId);
|
||||
};
|
||||
}, [interval, state]);
|
||||
return [state, { start, stop }];
|
||||
};
|
||||
|
||||
export default useInterval;
|
Reference in New Issue
Block a user