关于我需要回答的setTimeout的问题 [英] Question about setTimeout that I need answer to

查看:89
本文介绍了关于我需要回答的setTimeout的问题的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

所以我们都知道setTimeout在执行某事之前会等待一段时间。我的问题是,是否等待上面的代码先完成执行,等待一秒钟执行其他操作,或者只是等待一秒钟,以及上面的代码是否已经完成执行,它执行其余的代码呢?

So we all know setTimeout waits a certain amount of time before executing something. My question is, does it wait for the above code to finish executing first, before waiting a second to execute something else, or does it just wait for a second, and whether or not the above code has finished executing, it executes the rest of the code anyways?

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

var theTime = 1000;
var timeout = setTimeout("location.reload(true);", theTime);
function resetTimeout() {
clearTimeout(timeout);
timeout = setTimeout("location.reload(true);", theTime);
} //end of function resetTimeout()

我的目标是获得第一部分完成执行的代码,然后在代码的第一部分完成执行后立即刷新页面。有没有办法做到这一点?

My goal is to get the first part of the code to finish executing, then refresh the page as soon as the first part of the code has finished executing. Is there a way to do that?

推荐答案

在您的情况下,页面将在之后重新加载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);

这篇关于关于我需要回答的setTimeout的问题的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆