humo Wells
humo Wells

Reputation: 13

Faced problem with interval not being cleared in React

I was doing a project in React and what I wanted to do is to start the calculation of factorial of 1000 on start button and cancel the calculation on cancel button click. Thus, I used setInterval here is the whole code:

import React, { useState } from "react";

const Button = ({ title, countButton }) => {
  const [result, setResult] = useState(0);

  let interval;

  const handleFactorial = (num) => {
    let iteration = 1;
    let value = 1;

    interval = setInterval(function () {
      value = value * iteration;
      console.log(iteration++);
      if (iteration === num) {
        setResult(value);
        console.log(result);
        clearInterval(interval);
      }
    }, 0);
  };

  let cancelFactorial = () => {
    clearInterval(interval);
  };

  return countButton ? (
    <button onClick={() => handleFactorial(1000)}>{title}</button>
  ) : (
    <button onClick={cancelFactorial}>{title}</button>
  );
};

export default Button;

The problem is when I click on cancel button which is this one <button onClick={cancelFactorial}>{title}</button> but calculation keeps going. Thus I need your help

Upvotes: 0

Views: 66

Answers (2)

Dennis Vash
Dennis Vash

Reputation: 53884

You should use a reference for that as if you log your interval value, you will notice that you re-assign its value on every render.

const Button = ({ title, countButton }) => {
  const intervalRef = useRef();

  const handleFactorial = (num) => {
    intervalRef.current = setInterval(function () {...}, 0);
  };

  let cancelFactorial = () => {
    clearInterval(intervalRef.current);
  };
...
}

Upvotes: 1

HHK
HHK

Reputation: 1507

You need to use [useRef][1] to keep a reference to your interval.


// don't do that
// let interval;


// do this instead
const intervalRef = useRef();

interval.current = setInterval(function () { ... })


const cancelFactorial = () => {
    clearInterval(interval.current);
 };

Upvotes: 0

Related Questions