1

I need help in understanding why this code snippet changes the window location to facebook website but not to stackoverflow. Does location.href take some time to execute in the browser that the engine executes the next set of statements before changing the location?

function fb(){
    console.log("fb");
    location.href="https://facebook.com";
}
function so(){
    console.log("so");
    location.href="https://stackoverflow.com";
} 
function run(){
    setTimeout(fb);
    so();
} 
run();
Abhishek
  • 1,130
  • 1
  • 12
  • 25
  • 3
    I'm guessing it's something unique to location.href where it doesn't block or happen immediately. You can recreate the same behavior by testing `location.href="https://stackoverflow.com"; location.href="https://facebook.com";`. So setting location.href is probably somewhat of an asyncronous process since it probably calls some native browser (C/C++ ?) code to start the navigation process. The second line of javascript will always run way before the browser gets very far in loading a new page. Just making an educated guess here, though. – matmo Mar 16 '18 at 22:19
  • @matmo Makes sense. Is it documented somewhere? – Abhishek Mar 16 '18 at 22:21
  • This is related to this https://stackoverflow.com/questions/37521172/is-javascript-location-href-call-is-asynchronous – callback Mar 16 '18 at 22:25
  • @callback yes it seems related. This test also appears to show that multiple consecutive `location.href` statements result in the location change that's done by the last statement. – Abhishek Mar 16 '18 at 22:31

0 Answers0