Question about setTimeout that I need answer to

后端 未结 3 1943
你的背包
你的背包 2021-01-20 22:20

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 waitin

3条回答
  •  太阳男子
    2021-01-20 22:44

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

提交回复
热议问题