I'm only learning JS, and as I understand if you have some long script and while script is performs user leaves page - script will still work to it's end, right?
For example, I have custom 404 page and on page I have script what will redirect user after 5 second to main page. It's look like this:
<script>
var redirecting = document.getElementById("count_down");
var counter = 5;
var newElement = document.createElement("p");
newElement.innerHTML = "You will be redirected to main page in 5 seconds.";
var id;
redirecting.parentNode.replaceChild(newElement, redirecting);
id = setInterval(function () {
counter--;
if(counter < 0) {
newElement.parentNode.replaceChild(redirecting, newElement);
window.location.replace('<%= root_path %>');
} else {
newElement.innerHTML = "You will be redirected to main page in " + counter + " seconds.";
}
}, 1000);
</script>
Pretty simple script. But if user will click on menu link (for example "About Us") while script is counting, he will be redirected to "About us" page and when JS counter var will hit 0 he will be redirected to main page. But he already visited "About us" and will be redirected to main from "About us". Hope I make my self clear.
So, my question is: "How can I prevent JS perform, if user leaved page with script?"