有时Settimeout在使用效果中多次执行
这是我的Settimeout代码在使用效果中,我需要在其中每28分钟派遣操作。为了延迟,我正在使用一个动态值,即从实际API到当前时间和一个时间之间的差异。因此,每次它在指定的时间呈现时都会运行。
const isLogged = useSelector((state) => state.userReducer.loggedIn); // provide boolean value
const intervalId = useRef(null);
const nextRefreshCallValue = localStorage.getItem("nextCall")
useEffect(() => {
timeoutId.current = setTimeout(() => {
// To check in between if user is logged out and to stop setTimeout
if (!isLogged) {
clearTimeout(timeoutId.current);
return;
}
dispatch(refreshUserToken());
}, 1000 * moment(currentTime).diff(moment(nextRefreshCallValue))); //it will give diff in milliseconds
return () => {
clearTimeout(timeoutId.current)
}
}, [nextRefreshCallValue, isLogged])
它是按预期运行的,但是有时候,当我在多个浏览器选项卡中运行应用程序时,我可以看到超时在接下来的令牌呼叫(28分钟)之前的多次执行(28分钟),在这里我不使用setInterval,因为我们可以保持动态值每个浏览器选项卡中的新渲染时间。
我的最终要求是 - 所有标签都应同时接听API调用,并且应在28分钟后反复致电。
有人可以指导我在这里犯什么错误,以及如何避免这些情况?
Here is my setTimeout code in useEffect, where I need to dispatch an action every 28 minutes. For delay, I am using a dynamic value of taking the difference between the current time and a time from the actual API. So that every time it renders it runs at the specified time.
const isLogged = useSelector((state) => state.userReducer.loggedIn); // provide boolean value
const intervalId = useRef(null);
const nextRefreshCallValue = localStorage.getItem("nextCall")
useEffect(() => {
timeoutId.current = setTimeout(() => {
// To check in between if user is logged out and to stop setTimeout
if (!isLogged) {
clearTimeout(timeoutId.current);
return;
}
dispatch(refreshUserToken());
}, 1000 * moment(currentTime).diff(moment(nextRefreshCallValue))); //it will give diff in milliseconds
return () => {
clearTimeout(timeoutId.current)
}
}, [nextRefreshCallValue, isLogged])
It is running as expected, but sometimes when I run the application in multiple browser tabs I can see the timeout is getting executed various times before the next token call (28 minutes), Here I am not using setInterval because we can keep dynamic value every time on new renders in each browser tab.
My final requirement is -
All tabs should get the API call at the same time, and it should call after 28 minutes repeatedly.
Can someone please guide me on what mistake I am making here, and how to avoid those situations?
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论