Question about setTimeout that I need answer to

2020-04-10 02:10发布

问题:

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:

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.

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);

EDIT: 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);


回答2:

If you setTimeout to a very small value (e.g. 1ms, possibly even zero, but haven't checked that) it will execute as soon as your main code is finished. It won't execute before your main code is finished, because JavaScript is not multi-threaded.



回答3:

JavaScript is single-threaded and non-preemptive, it's not possible to interrupt code that's running. Asynchronous code, such as timeouts and AJAX callbacks, cannot run until the currently executing code returns to the main event loop.

The timer in setTimeout starts immediately when it's called. But because of the single-threaded design, the callback can't be called until all your current JS finishes. If that takes longer than the timer, then the callback will be delayed. So all you're guaranteed is that the callback will be called in at least that amount of time -- it might be longer, but not shorter. There could also be other asynchronous callbacks ahead of it in the event queue.