0

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?"

Andrey Drozdov
  • 571
  • 1
  • 5
  • 22
  • Hint: There’s an `unload` and a `beforeunload` event. – Sebastian Simon Sep 14 '16 at 23:12
  • If I get it right, i must do: `$(document).beforeunload() {enter my script here}` – Andrey Drozdov Sep 14 '16 at 23:15
  • Possible duplicate of [Best way to detect when a user leaves a web page?](http://stackoverflow.com/questions/147636/best-way-to-detect-when-a-user-leaves-a-web-page) – VLAZ Sep 14 '16 at 23:20
  • All scripts stop when the window is reloaded with a different page. So unless the `About Us` link opens a new window, you shouldn't have a problem. – Barmar Sep 14 '16 at 23:26
  • no..when user leaves page the window and all scripts are removed and a new window is created for new page – charlietfl Sep 14 '16 at 23:26
  • 2
    It doesn't work like that. When You leave page, scripts that are "connected" to previous page are not executing. You have new page with new scripts. Simple. – instead Sep 14 '16 at 23:26
  • I'm sure that all of you are right, but the fact is that it still redirecting if I leaving 404 page. And I really don't understand why. – Andrey Drozdov Sep 14 '16 at 23:47

0 Answers0