All files / src/useClock useClock.ts

100% Statements 12/12
50% Branches 1/2
100% Functions 5/5
100% Lines 12/12

Press n or j to go to the next uncovered block, b, p or k for the previous block.

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 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52                    10x                                 10x 10x   10x   10x 10x             10x 6x 6x 6x 6x         10x    
import { useCallback, useEffect, useRef } from "react";
 
import { SubscriptionManager, useSubscription } from "../useSubscription";
 
/**
 * time to next full minute from the date
 * @param millisSinceEpoch - millis since epoch time.
 * @returns milliseconds to next full minute from date
 */
function timeToNextFullMinute(millisSinceEpoch: number): number {
  return 60000 - (millisSinceEpoch % 60000);
}
/**
 * This hook notifies the subscribers with the current date.  This
 * is useful for updating components that show moment in time without
 * a full rerender of the tree.
 *
 * It notifies at the following points:
 * - useEffect
 * - first minute at zero seconds
 * - every minute after at zero seconds
 *
 * However, due to the performance of the device, this may not be acurate.
 *
 * @returns subscription manager
 */
export function useClock(): SubscriptionManager<number> {
  const { subscribe, notify, useSubscribeEffect } = useSubscription<number>();
  const timeoutRef = useRef<ReturnType<typeof setTimeout>>();
 
  const doNotify = useCallback(
    function doNotify() {
      notify(Date.now());
      timeoutRef.current = setTimeout(
        doNotify,
        timeToNextFullMinute(Date.now())
      );
    },
    [notify]
  );
  useEffect(() => {
    doNotify();
    return () => {
      Eif (timeoutRef.current) {
        clearTimeout(timeoutRef.current);
      }
    };
  }, [doNotify]);
 
  return { subscribe, notify, useSubscribeEffect };
}