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
}

```
Don't know if it is a best practice but you can use localStorage.

```
if((localStorage.getItem('pageLoaded') ?? 'true') === 'true') {
   alert('dsds')
   localStorage.setItem('pageLoaded', 'false')
}

```

The alert will be executed once