Update selected item color in Pass menu
[ProtonMail-WebClient.git] / packages / pass / hooks / useCountdown.ts
blobf2f3b4756ecf2cd25ea2f6c7f2a6b2e894aacb70
1 import { useEffect, useMemo, useRef, useState } from 'react';
3 import type { Maybe } from '@proton/pass/types';
5 export const useCountdown = (initial?: number) => {
6     const interval = useRef<Maybe<NodeJS.Timeout>>();
7     const [value, setValue] = useState<number>(0);
9     const handle = useRef({
10         start: (value: number) => {
11             clearInterval(interval.current);
12             setValue(value);
13             interval.current = setInterval(
14                 () =>
15                     setValue((prev) => {
16                         if (prev === 0) clearInterval(interval.current);
17                         return Math.max(0, prev - 1);
18                     }),
19                 1_000
20             );
21         },
22         cancel: () => {
23             clearInterval(interval.current);
24             setValue(0);
25         },
26     });
28     useEffect(() => {
29         if (initial) handle.current.start(initial);
30         return handle.current.cancel;
31     }, []);
33     return useMemo(() => [value, handle.current] as const, [value]);