Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

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]);
};

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

>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]);
};
Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading