Question: So I am trying to implement an auto language changer for my webpage.
But it keeps refreshing the page as it keeps running.
I want to run this script only once so it doesn't refresh my page forever.

I have this script:

```
var language = navigator.language || navigator.userLanguage;

language = language.substring( 0, 2 );

if  (language == "pt" || "pt-BR" || "pt-PT"){
window.location.href = "index.html";
}

else {
window.location.href = "indexEN.html";  //
}

```

And its called by:

```
        <!-- Auto Language -->
        <script src="js/language.js"></script>

```

Answer: 
Think about it as if you have an infinite loop, like `while (true) {}` — what you need to do is break out of the loop at some point. To break out of this loop, you need to add a check to make sure you're not already on the intended page. That will stop the constant redirection.

```
var language = navigator.language || navigator.userLanguage

language = language.substring(0, 2)

var ptPage = 'index.html'
var enPage = 'indexEN.html'
// you're calling substring, so no need to check the variants
// your check was also incorrect :)
if (language == "pt") {
  if (window.location.pathname !== '/' + ptPage) {
    window.location.href = ptPage
  }
} else if (window.location.pathname !== '/' + enPage) {
  window.location.href = enPage
}

```
Refreshing the page is part of your code, as you can see here

```
var language = navigator.language || navigator.userLanguage;// get users default language

language = language.substring( 0, 2 );

if  (language == "pt" || "pt-BR" || "pt-PT"){
window.location.href = "index.html";
}
else {
window.location.href = "indexEN.html";  //loading another html file for users who use english
}

```

So since you are reloading another html file, your javascript IS going to run again. A solution to this would be to make your webpage a SPA (single page application). That way you wouldn't have to reload anything (including javascript). You can also change page content and headers without actually loading a new file. SPA's are usually done in react (with react routing) but you can make then vanilla JS too.
<https://medium.com/altcampus/implementing-simple-spa-routing-using-vanilla-javascript-53abe399bf3c>