Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Is JavaScript location.href call asynchronous?

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!

like image 305
shreyansh Avatar asked May 30 '16 08:05

shreyansh


People also ask

Is window location href async?

@shreyansh It is asynchronous in the broadest terms, my comment relates to how much can be completed prior to the transition..

What does location href do in Javascript?

The location. href property sets or returns the entire URL of the current page.

What happens after window location href?

window.location.href returns the href (URL) of the current page. window.location.hostname returns the domain name of the web host. window.location.pathname returns the path and filename of the current page.


1 Answers

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).

like image 161
ŹV - Avatar answered Oct 03 '22 15:10

ŹV -