Is JavaScript location.href call is asynchronous?

2019-02-16 19:12发布

问题:

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??");
}

If you see 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 .

So my question is , "Is location.href call is asynchronous in nature, if not then what is happening over here" ??

Because I thought the moment it will redirect the user to other page, the lines of code below it will never execute.

Any help/explanation is appreciated!!!

Thanks

回答1:

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 browsers speed or later synchronous input from the user (an alert in your case).