Is JavaScript location.href call asynchronous?
Asked Answered
P

1

22
function fun(){
    console.log("Hi");
    window.location.href="http://www.google.com";
    console.log("Hello, how are you");
    alert("I am good");
    fun1();
}

function fun1(){
    console.log("Whats up??");
}

In the above lines of code the location.href is getting called before console.log("Hello, how are you"), alert and fun1().

When I call the fun() it executes all the statements below location.href and then it redirects to https://www.google.com. Is the location.href call asynchronous in nature, and if not then what is happening?

I thought the moment it redirects the user to other page, the lines of code below it would never execute.

Any help/explanation is appreciated!

Peale answered 30/5, 2016 at 8:38 Comment(0)
F
11

A browser will execute code after window.location.href = "http://google.com" until the browser goes to the next web address. As such, the number of lines that will be executed depends on some combination of the browser's speed or later synchronous input from the user (an alert in your case).

Fonz answered 30/5, 2016 at 8:44 Comment(7)
but in my case it is executing all the line of code before actually redirecting to google.comPeale
So what should I understand from your comment ?? it is synchronous or asynchronous??Peale
@Peale It is asynchronous in the broadest terms, my comment relates to how much can be completed prior to the transition..Fonz
"A browser will execute code ..." - so is that a standard? Can you point to some standard reference for this behaviour?Lyon
@TJ This issue is not explicitly addressed, but as many pieces of Javascript framework documentation have pointed out, the protocol for execution independent of navigation is: html.spec.whatwg.org/multipage/…Fonz
Mind that alert, confirm etc. dialogs always block JS i.e. if you use alert after location.href it will not let it redirect until the alert is closed. As for how many statements can be executed is purely depend on the speed of your internet. It will keep executing current page's JS till the first byte of the new page is rendered in the browser.Julianajuliane
What is that "until"? What is the behavior of href with respect to Call Stack, Event/Call Back Queue (that is how it behaves when Events and AJAX calls are around in the scenario)? If there is sync wait after href it always waits for it and never breaks the while loop in between! So it gives an impression that it goes into the CallBack queue, but actually seem not to (explanation in the question #51468562 ) !Potboiler

© 2022 - 2024 — McMap. All rights reserved.