2019-11-18 23:37:36 +00:00
|
|
|
import { useState, useCallback, useEffect } from "react";
|
|
|
|
|
|
|
|
export function useTimer(timeoutMs: number): [number, () => void, () => void] {
|
|
|
|
const Interval = 100;
|
|
|
|
const [startDate, setStartDate] = useState(undefined as Date | undefined);
|
|
|
|
const [percent, setPercent] = useState(0);
|
|
|
|
|
|
|
|
const trigger = useCallback(() => {
|
|
|
|
setPercent(0);
|
|
|
|
setStartDate(new Date());
|
|
|
|
}, [setStartDate, setPercent]);
|
|
|
|
|
|
|
|
const clear = useCallback(() => {
|
|
|
|
setPercent(0);
|
|
|
|
setStartDate(undefined);
|
|
|
|
}, []);
|
|
|
|
|
|
|
|
useEffect(() => {
|
|
|
|
if (!startDate) {
|
|
|
|
return;
|
|
|
|
}
|
|
|
|
|
|
|
|
const intervalNode = setInterval(() => {
|
2021-01-02 10:58:24 +00:00
|
|
|
const elapsedMs = startDate ? new Date().getTime() - startDate.getTime() : 0;
|
|
|
|
let p = (elapsedMs / timeoutMs) * 100.0;
|
2019-11-18 23:37:36 +00:00
|
|
|
if (p >= 100) {
|
|
|
|
p = 100;
|
|
|
|
setStartDate(undefined);
|
|
|
|
}
|
|
|
|
setPercent(p);
|
|
|
|
}, Interval);
|
|
|
|
|
|
|
|
return () => clearInterval(intervalNode);
|
|
|
|
}, [startDate, setPercent, setStartDate, timeoutMs]);
|
|
|
|
|
2021-01-02 10:58:24 +00:00
|
|
|
return [percent, trigger, clear];
|
|
|
|
}
|