Search code examples
ruby-on-railsruby-on-rails-5setintervalturbolinksturbolinks-5

Turbolinks 5 and setInterval issue


I'm using Turbolinks 5 with Rails 5 and I'm setting a JS interval in order to refresh page content each 10 seconds through AJAX:

<script type="text/javascript">
  $(document).ready(function() {
    function fetchContent() {
      // some AJAX request
    }

    setInterval(fetchContent, 10000);
  });
</script>

When I first load the page containing the above code, it works: the fetchContent is fired every 10 seconds.

However, when I navigate to another page, the fetchContent keeps firing. Moreover, when I go back to the page (using the browser back button), the fetchContent fires unpredictably multiple times. Obviously, this is not the wanted behaviour.

How to fix this?


Note: To fix this, I know I could need a clearInterval call of some sort, but how should I make it using Turbolinks 5 e.g. what event should I bind? Since Turbolinks 5, API has changed. In particular, all of the Turbolinks Classic events have been renamed, and several—including page:update—have been removed, so I cannot use solutions like this, this or this.


Solution

  • Maybe I found a solution. In application.js I stated:

    function setIntervalWithTurbolinks(intervalFunction, milliseconds) {
      var interval = setInterval(intervalFunction, milliseconds);
    
      $(document).on('turbolinks:before-cache turbolinks:before-render', function() {
        clearTimeout(interval);
      });
    }
    

    So, in my application, I use it this way:

    setIntervalWithTurbolinks(fetchContent, 10000);