有时Settimeout在使用效果中多次执行

发布于 2025-02-08 11:03:21 字数 1005 浏览 2 评论 0原文

这是我的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 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。
列表为空,暂无数据
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文