Non puoi selezionare più di 25 argomenti Gli argomenti devono iniziare con una lettera o un numero, possono includere trattini ('-') e possono essere lunghi fino a 35 caratteri.
 
 
 
 

58 righe
1.4 KiB

  1. import { useEffect } from 'react';
  2. import useCommittedRef from './useCommittedRef';
  3. /**
  4. * Creates a `setInterval` that is properly cleaned up when a component unmounted
  5. *
  6. * ```tsx
  7. * function Timer() {
  8. * const [timer, setTimer] = useState(0)
  9. * useInterval(() => setTimer(i => i + 1), 1000)
  10. *
  11. * return <span>{timer} seconds past</span>
  12. * }
  13. * ```
  14. *
  15. * @param fn an function run on each interval
  16. * @param ms The milliseconds duration of the interval
  17. */
  18. function useInterval(fn, ms, paused, runImmediately) {
  19. if (paused === void 0) {
  20. paused = false;
  21. }
  22. if (runImmediately === void 0) {
  23. runImmediately = false;
  24. }
  25. var handle;
  26. var fnRef = useCommittedRef(fn); // this ref is necessary b/c useEffect will sometimes miss a paused toggle
  27. // orphaning a setTimeout chain in the aether, so relying on it's refresh logic is not reliable.
  28. var pausedRef = useCommittedRef(paused);
  29. var tick = function tick() {
  30. if (pausedRef.current) return;
  31. fnRef.current();
  32. schedule(); // eslint-disable-line no-use-before-define
  33. };
  34. var schedule = function schedule() {
  35. clearTimeout(handle);
  36. handle = setTimeout(tick, ms);
  37. };
  38. useEffect(function () {
  39. if (runImmediately) {
  40. tick();
  41. } else {
  42. schedule();
  43. }
  44. return function () {
  45. return clearTimeout(handle);
  46. };
  47. }, [paused, runImmediately]);
  48. }
  49. export default useInterval;