且构网

分享程序员开发的那些事...
且构网 - 分享程序员编程开发的那些事

关于我需要回答的setTimeout的问题

更新时间:2023-12-02 18:16:28

在您的情况下,页面将在之后重新加载1秒调用了setTimeout 。所以它是巨大的代码块时间再加上1秒。

In your case, the page will reload 1 second after setTimeout was called. So it's the "huge chunk of code" time plus 1 second.

要在代码的第一部分完成后立即刷新页面,只需调用 location.reload 没有 setTimeout

To refresh the page as soon as the first part of the code finishes, just call location.reload without setTimeout:

if (1) {
  //huge chunk of code
}

location.reload(true);

编辑:这种方法不等待异步代码完成。例如,下面的程序会在警告框弹出之前被重新加载中断。

This approach doesn't wait for asynchronous code to finish. For example, the program below is interrupted by the reload before the alert box pops up.

if (1) {
  setTimeout(() => alert('Test'), 1000);
}

location.reload(true);