简体   繁体   中英

Stopping javascript running when a link is clicked

I was wondering if it is possible to stop javascript running on a page when a link is clicked. The problem i am having is the pages refreshes every 30 seconds (A list needs to be up to date on the site) But if a user clicks a link from the list and before that has finished loading the 30 second refresh begins, it stops the link from opening and instead refreshes the page.

Here is the script that is running,

        <script type="text/javascript">
        window.name = "NewRegistration";
        setTimeout("location.reload(true);",30000);
    </script>

The link is to another page on the site.

If anything is not clear please ask.

Thanks,

Jack.

<script type="text/javascript">
  var id;

  function stopRefresh()
  {
    window.clearTimeout(id);
  }

  window.name = "NewRegistration";
  id = window.setTimeout("location.reload(true);",30000);
</script>

<a href="somelike.html" onclick="stopRefresh();">Some Link</a>

If you're using jQuery, this is much easier to apply to all the links on the page:

<script type="text/javascript">
  $(document).ready(function() {
    $('a').click(function() {
      stopRefresh();
    });
  });
</script>

You don't have to stop all the javascript on the Page.

You have to work on your refreshing page function. For example you can set a flag to false when a link is clicked.

After 30sec if (flag == false) do not refresh the page else refresh the page

That's all :)

The most common way of doing this these days is to update in the background without reloading the entire page, though that's a bit more work to set up. Read up on Ajax to learn more.

A solution that is simpler to implement is to... well, Sean Bright already beat me to that just now I see ;)

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM