2

I am trying to make a timer that will start at the beginning of the sorting visualization and run until sorting is over. The timer starts accordingly but does not stop after sorting. this works absolutely fine in functional Component (with useEffect hook) but does not work in class Component.

here is my startTimer function -

startTimer = () => {
       let isAlgo = this.state.isAlgorithmSortOver;
       let interval;
       if (isAlgo === true) {
           interval = setInterval(() => {
               this.setState({
                   time: this.state.time + 10,
               });
           }, 10);
       } else if (isAlgo === false) {
           clearInterval(interval);
       }
       // return () => clearInterval(interval);
   };

and here is startVisualizer function -

startVisualizer = () => {
        let steps = this.state.arraySteps;
        let colorSteps = this.state.colorSteps;

        this.clearTimeouts();

        let timeouts = [];
        let i = 0;

        while (i < steps.length - this.state.currentStep) {
            let timeout = setTimeout(() => {
                let currentStep = this.state.currentStep;
                this.setState({
                    array: steps[currentStep],
                    colorElement: colorSteps[currentStep],
                    currentStep: currentStep + 1,
                    isAlgorithmSortOver: false,
                });
                //? comparing the currentStep with arraySteps and the state of isAlgorithmSortOver will remain false until the array is fully sorted.. Adding '+ 1' to currentStep because the arraySteps  state always will be '+1' bigger than the currentStep..
                if (currentStep + 1 === i) {
                    this.setState({
                        isAlgorithmSortOver: true,
                    });
                }

                timeouts.push(timeout);
            }, this.state.delayAnimation * i);
            i++;
        }
        this.startTimer();

        this.setState({
            timeouts: timeouts,
            // isAlgorithmSortOver: false,
        });
    };
Saif789
  • 69
  • 3

1 Answers1

1

because you are not clearing the interval. Try to save interval's id to state like this:

startTimer = () => {
       let isAlgo = this.state.isAlgorithmSortOver;
       if (isAlgo === true) {
           interval = setInterval(() => {
               this.setState({
                   time: this.state.time + 10,
               });
           }, 10);
           this.setState({interval})
       }
   };

Then you can then call clearInterval wherever you want, like this:

   clearInterval(this.state.interval)

You also should bring out timeouts.push(timeout) from setTimeout where in while. Because, otherwise timeouts.push(timeout) does not work synchronously, it works after a while.