问题
I took a look at this is-javascript-location-href-call-is-asynchronous and this what the heck is the event loop anyway but there is no explanation of the defined behavior of href
of window.location
:
The following is the script order in source code:
1. DOM elements
2. <script> at the bottom having doc.ready.
3.Further <script> tags.
4. doc.ready's callback goes into the CB queue because all DOM elements are available in step 1 and there are only further script tags
( This callback stays in the queue until all the scripts in step 3 complete its execution and empties the call stack. Correct? )
5. window.location.href=/error inside the fail() of sync AJAX. It does not immediately redirect. So it is async.
// synchronous wait method ~ >= 0.5sec inside this fail() method just after (for testing)
[TAG: 1]
6. call stack becomes empty here as there no more scripts to exec
Question: If href
also acts like Events/XHR/Timeouts, does href
at step 5
go into the event queue? If so, exactly when ? ( Events, AJAX, setTimeouts have defined behavior of when it gets into the queue but what about href
redirection? )
Experiment: If the synchronous wait is there after step 5
, then href
redirection happens "most" of the times. But "sometimes" doc.ready
's callback is also executed.
Question: If href
acts like Event/XHR/Timeouts, then it is always the second in the queue after doc.ready
and so even with the synchronous wait, it should always execute after doc.ready
. But it did not based on the above experiment!! So it shows href
does not involve event queues, right? Then, what is the defined behavior of href
when other Events/XHR/Timeouts are around and relate to Call Stack or Event/CB Queue ?
回答1:
Stop. Research Javascript Event Loop. JS executes code linerly. When an event - asynchronous call generally speaking - is encountered it is pushed to an "event queue" and JS execution keeps going. The event queue is 'first in, first out'. There's no telling what is in the queue at any moment so the execution of any given event - your href - is unpredictable - it is not 'by chance.' If program execution was 'by chance', then computers would not even work.
来源:https://stackoverflow.com/questions/51468062/javascript-execution-order-when-window-location-href-happens