javascript - 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 之后,持续时间应该停止增加,但事实并非如此!谢谢回答
解决方案
问题是每次调用组件函数来渲染组件时(在任何一系列状态更改之后),都会创建一个新 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);
};
推荐阅读
- ruby-on-rails - Rails/ActiveRecord:如何在一个表中找到指向另一个匹配所有指定列值的行的行?
- python - 如何从类中获取每个变量实例的列表?
- google-sheets - gspread: 503 服务当前不可用
- powerbi - 数据结构问题
- c# - 如何使用 Dapper 从 SQL Server Image 字段中读取 blob 数据?
- combobox - 网格中的 Vaadin 组合框在单击时不显示下拉菜单
- c - 检查字母表中的所有字母是否出现在没有重复的文件中
- git - 从 export-subst 获取最新的 git 标签
- kotlintest - 实现 TestCaseExtension 时如何记录特定于测试的信息?
- python - 如何在没有中间视图的情况下立即更新 ipyvolume 形状