Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Why changing `window.location.href` doesn't work as a return?

I would have expected, that in the following function the first window.location.href works as a return, gets redirected to example.com, and the rest of the code would be ignored.

() => {
  window.location.href = 'http://example.com/'; // Does nothing
  console.log('does it log?'); // Yes, it logs
  window.location.href = 'http://example.org'; // Redirects here
}

Navigating to another page sounds like a definitive stop: discard DOM, abandon XHR queries, leave the site etc. Why the rest is still executed?

like image 881
Balázs Herczeg Avatar asked Aug 30 '26 05:08

Balázs Herczeg


1 Answers

Short answer - it depends on the browser's speed of doing the redirect to the other page, hence unpredictable.

What's happening here is that the browser will try to execute the code after

window.location.href = 'http://example.com/';

Until the redirect occures and the page will go to the next web adress the rest of the code will execute as it supposed to run regular so the number of lines of code that will be executed actually depends on the browser's speed of doing the actual redirecting.

like image 194
Ran Turner Avatar answered Aug 31 '26 20:08

Ran Turner