-1

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]

  1. 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 ?

Brian Tompsett - 汤莱恩
  • 5,753
  • 72
  • 57
  • 129
user104309
  • 690
  • 9
  • 20

1 Answers1

0

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.

radarbob
  • 4,964
  • 2
  • 23
  • 36
  • I edited the question. Please check. I understand call stack, event loop and callback queue. Saw the JSConf video. `doc.ready` goes into the callback queue when DOM elements are ready. But is there any definite way of knowing when does the `href` event (if at all it is an event) goes into the queue? Even `href` is assumed to make use of event queues, `href` does not conform to the working of the event queue based on the experiment. – user104309 Jul 23 '18 at 02:57
  • Is my question clear now? Can you please take a look? – user104309 Aug 01 '18 at 07:24