When you navigate to a new page, the existing page is shut-down completely. The Javascript context is stopped and thrown away. Whether this shut-down happens immediately, after a few lines of code, after a bunch of lines of code is completely variable. It likely has to do with some async timing while the new page loading is initiated.
Over the years there has been some slight difference in how some browsers treated the next few lines of code after setting a new location, but you should never count on any lines executing after you set a new location because setting a new location is telling the browser to shut down this page and start loading a new one.
A quick test in Chrome shows that an alert()
on the very next line does execute and wait for user input before it finishes loading the next location, but this is undocumented behavior and is not safe to count on.
In Firefox, the alert briefly flashes on screen, but does not wait for user input and the new page is loaded.
The smart way to code is to not place any code after setting the window.location
. That way, you will not be relying on a behavior that varies among browsers and all browsers will behave the same with your code. If you want to execute something else, then do it BEFORE you change the window.location
. Or, if you want your current block of code to finish executing, then change the location in a setTimeout()
as in:
setTimeout(function() {
window.location = "http://www.stackoverflow.com";
}, 1);
This would then reliably let the current thread of execution finish before the page was changed to a new location because setTimeout()
works via an event queue and it's event won't be processed until after the current thread of execution is done (no matter how long it takes to complete).