繁体   English   中英

反应 clearInterval 在 class 组件中不起作用

[英]React clearInterval not working in class Component

我正在尝试制作一个计时器,该计时器将在排序可视化开始时开始运行,直到排序结束。 计时器相应地启动,但在排序后不会停止。 这在功能组件(使用 useEffect 挂钩)中工作得非常好,但在 class 组件中不起作用。

这是我的 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);
   };

这里是 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,
        });
    };

因为你没有清除间隔。 尝试将间隔的 id 保存到 state ,如下所示:

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

然后你可以在任何你想要的地方调用 clearInterval ,如下所示:

   clearInterval(this.state.interval)

您还应该从 setTimeout where in while中取出timeouts.push(timeout) 因为,否则timeouts.push(timeout)不会同步工作,它会在一段时间后工作。

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM