42

When writing server-side code you need to explicitly stop execution after sending a "Location: ..." header to the client or your code will continue to execute in the background.

But what about when you change window.location in a client-side script? Does this immediately stop execution of the current script or is it up to the programmer to make sure that any code located after this call is not reached?

Aleksander Kmetec
  • 3,287
  • 2
  • 24
  • 19
  • @DavidAndersson What else would your +1 imply? – stolsvik Aug 29 '14 at 11:26
  • @stolsvik almost anything, including it is useful, shows research effort, and is clear. Maybe it is also just worth reading, funny, intriguing, etc? – Andrew Aug 19 '15 at 01:54
  • I had to explicitly call `return;` on the next line to get out of the flow and let window.location do its thing. – VPaul Apr 01 '20 at 16:47

2 Answers2

22

Does this immediately stop execution of the current script

No, the remaining handler script will execute to the end before control returns to the browser and events start happening. When loading of the new page gets far enough for ‘navigation’ to occur, the beforeunload and unload events will fire, then the page and any script in it will become inactive.

However, any further queued events and timeouts might not fire. For example if you navigate the page in a click handler of a form submit button and don't cancel the default action, it is possible (race condition) for the navigation to occur before the submit event queued by the default action of the click.

bobince
  • 528,062
  • 107
  • 651
  • 834
  • 4
    Thanks. As a corollary to this question, is there any way to detect when you're in this state (i.e., `window.location` has changed but navigation has not yet occurred)? – speedplane Apr 12 '15 at 22:01
  • Thanks, just the answer I needed. Is your answer based on observing how browsers work, or is this behavior defined somewhere? – Tomasz P. Szynalski Aug 25 '17 at 16:43
  • 1
    The answer was based on observation, but some work has been done in HTML5 on standardising browser control flow—asee eg https://www.w3.org/TR/html5/webappapis.html#event-loops, https://www.w3.org/TR/html5/browsers.html#navigate. The standards we have ended up with are largely unreadable, and still leave a bunch of stuff unspecified, but we're still in a better situation than the inconsistent and mysterious one we had before. – bobince Aug 25 '17 at 21:47
15

Setting window.location does not implicitly stop JS execution. Take the following as an example:

function locationTest() {
  window.location = 'http://www.google.com/';
  window.open('http://www.yahoo.com/');
}

locationTest();

Try running that from Firebug/Web Inspector/etc. and you'll notice that the current window will load Google, but a new window will open with Yahoo as well.

Jimmy
  • 35,686
  • 13
  • 80
  • 98