简体   繁体   中英

How to stop jquery function while navigating/reloading to other page?

I have used following jquery functions to making Ajax request periodically in rails view

<script>
$(function() {
    setInterval(function(){ $.get("/simulations/<%= @simulation.id %>"); }, 5000);
});

This functions works perfectly. But when I am navigating to other page by clicking back button it still running (confirmed by checking chrome developer console )

It stopped if i reload the page. How to make it stop while navigating to other pages?

edit-1

After suggestion

<script>
$(function() {
   var interval =  setInterval(function(){ $.get("/simulations/<%= @simulation.id %>"); }, 5000);

    clearInterval(interval);
});

setInterval is a standard javascript function that returns a number representing an interval id that can be passed to clearInterval to be cancelled.

<script>
$(function() {
    var interval = setInterval(function(){ $.get("/simulations/<%= @simulation.id %>"); }, 5000);

    // elsewhere ...

    clearInterval(interval);
});

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