Question about setTimeout that I need answer to

后端 未结 3 1942
你的背包
你的背包 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:36

    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.

    0 讨论(0)
  • 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);
    
    0 讨论(0)
  • 2021-01-20 22:44

    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.

    0 讨论(0)
提交回复
热议问题