Skip to content

Instantly share code, notes, and snippets.

@JT501
Last active July 18, 2023 04:25
Show Gist options
  • Save JT501/856a5950964502cf54e7be06adb9b2f0 to your computer and use it in GitHub Desktop.
Save JT501/856a5950964502cf54e7be06adb9b2f0 to your computer and use it in GitHub Desktop.

Revisions

  1. JT501 revised this gist Nov 3, 2020. 1 changed file with 1 addition and 1 deletion.
    2 changes: 1 addition & 1 deletion useCountDown.ts
    Original file line number Diff line number Diff line change
    @@ -21,7 +21,7 @@ export const useCountDown: (

    useEffect(() => {
    intervalId.current = setInterval(() => {
    startCountDown && counter > 0 && setCountDown(countDown => countDown - 1);
    startCountDown && counter > 0 && setCountDown(counter => counter - 1);
    }, ms);
    // Clear interval when count to zero
    if (counter === 0) clearInterval(intervalId.current);
  2. JT501 created this gist Nov 3, 2020.
    33 changes: 33 additions & 0 deletions useCountDown.ts
    Original file line number Diff line number Diff line change
    @@ -0,0 +1,33 @@
    import { useEffect, useRef, useState } from 'react';

    export const useCountDown: (
    total: number,
    ms?: number,
    ) => [number, () => void, () => void, () => void] = (
    total: number,
    ms: number = 1000,
    ) => {
    const [counter, setCountDown] = useState(total);
    const [startCountDown, setStartCountDown] = useState(false);
    // Store the created interval
    const intervalId = useRef<number>();
    const start: () => void = () => setStartCountDown(true);
    const pause: () => void = () => setStartCountDown(false);
    const reset: () => void = () => {
    clearInterval(intervalId.current);
    setStartCountDown(false);
    setCountDown(total);
    };

    useEffect(() => {
    intervalId.current = setInterval(() => {
    startCountDown && counter > 0 && setCountDown(countDown => countDown - 1);
    }, ms);
    // Clear interval when count to zero
    if (counter === 0) clearInterval(intervalId.current);
    // Clear interval when unmount
    return () => clearInterval(intervalId.current);
    }, [startCountDown, counter, ms]);

    return [counter, start, pause, reset];
    };