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?
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);
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With