首页 > 解决方案 > clearInterval 不清除间隔

问题描述

我知道这个问题已经被问过很多次了......但我认为我做的一切都是正确的,但它仍然无法正常工作,clearInterval 不会停止间隔,该函数仍然每 1 秒被调用一次。

这是我的完整代码:

  const [playerState, setPlayerState] = useState({ playing: true });
  let [duration, setDuration] = useState(0);

  let counter = null; 
  let count = () => {
    setDuration(++duration);
  };

  let handlePlay = () => {
    setPlayerState({ playing: true });
    counter = setInterval(count, 1000); //call count every 1 second, working fine
    console.log("playing");
    console.log(duration);
  };

  let handlePause = () => {
    setPlayerState({ playing: false });
    clearInterval(counter);   // doesn't work the function is still being called  every 1 second.
    console.log("paused");
    console.log(duration);
  };

在调用 handePlay 时,持续时间应该每 1 秒增加 1,这可以正常工作,在调用 handlePause 之后,持续时间应该停止增加,但事实并非如此!谢谢回答

标签: javascriptreactjs

解决方案


问题是每次调用组件函数来渲染组件时(在任何一系列状态更改之后),都​​会创建一个 counter的局部变量。您存储计时器句柄的那个不再存在。您必须将计时器句柄保存在以后可以使用的地方(基本上是状态或参考)。当您的组件卸载取消计时器时,您还需要确保有一个清理回调。

看评论:

const [playerState, setPlayerState] = useState({ playing: true });
let [duration, setDuration] = useState(0);

// A ref to hold the timer handle
const timerRef = useRef(0);

// Register an unmount callback
useEffect(() => {
    // The return value is the clean up callback
    return () => {
        clearInterval(timerRef.current);
    };
}, []); // <== Empty dependency array means callback is called on unmount only

let count = () => {
    setDuration(++duration);
};

let handlePlay = () => {
    setPlayerState({ playing: true });
    // *** Use the ref
    clearInterval(timerRef.current);
    timerRef.current = setInterval(count, 1000); //call count every 1 second, working fine
    console.log("playing");
    console.log(duration);
};

let handlePause = () => {
    setPlayerState({ playing: false });
    // *** Use the ref
    clearInterval(timerRef.current);
    timerRef.current = 0;
    console.log("paused");
    console.log(duration);
};

推荐阅读