clearInterval() fails to stop an interval running on a timer

First time using clearInterval() looking at other examples and the interval docs this appears to be the way to stop an interval. Not sure what I am missing.

The intention is to kill the timer when the currentStop prop updates.

import React, { useEffect, useState } from 'react';

type Props = {
  stopNumber: number;
  currentStop: number;
};

const timerComponent = ({ stopNumber, currentStop }: Props) => {
  let interval: NodeJS.Timer;

  // Update elapsed on a timer
  useEffect(() => {
    if (stopNumber === currentStop) {
      interval = setInterval(() => {
        console.log('timer is running');
      }, 3000);

      // Clear interval on unmount
      return () => clearInterval(interval);
    }
  }, []);

  // Clear timers that were running
  useEffect(() => {
    if (stopNumber !== currentStop) {
      clearInterval(interval);
    }
  }, [currentStop]);
};

>Solution :

Store the intervalId on a ref instead

const timerComponent = ({ stopNumber, currentStop }: Props) => {
  const intervalRef = useRef({
    intervalId: 0
  })

  // Update elapsed on a timer
  useEffect(() => {
    if (stopNumber === currentStop) {
      intervalRef.current.intervalId = setInterval(() => {
        console.log('timer is running');
      }, 3000);

      // Clear interval on unmount
      return () => clearInterval(intervalRef.current.intervalId);
    }
  }, []);

  // Clear timers that were running
  useEffect(() => {
    if (stopNumber !== currentStop) {
      clearInterval(intervalRef.current.intervalId);
    }
  }, [currentStop]);
};

Leave a Reply