3

I'm working on a Table that logs all action and refreshes the table based on the interval given. Everything works fine except when using setInterval, here's my code:

  var interval = 3000;
  var interval_en = true;

  $(document).ready(function() {
    $('#logs_tbl').DataTable();
    $('.paginate_button,.paginate_button.current').click(function(){
        e.preventDefault();
        console.log("paginate click");
        interval_en = false;
    }).change(function(e){
        e.preventDefault();
        console.log("paginate click");
        interval_en = false;
    });
    var aclogs_interval = setInterval(function () {
        if(interval_en){
            console.log("logging=true");
            aclog_refresh(); //This function refreshes the table via Ajax
        }else{
            console.log("logging stopped");
            clearInterval(aclogs_interval);
        }
    }, interval);
} );

What have I tried so far:

Different selector:

$('#logs_tbl_paginate a').click(function(){
   interval_en = false;
   clearInterval(aclogs_interval);
});

Binding per interval:

   var aclogs_interval = setInterval(function (e) {
        if(interval_en){
            console.log("logging=true");
            aclog_refresh();
            $('.paginate_button,.paginate_button.current').click(function(){
                e.preventDefault();
                console.log("paginate click");
                interval_en = false;
            }).change(function(e){
                e.preventDefault();
                console.log("paginate click");
                interval_en = false;
            });
        }else{
            console.log("logging stopped");
            clearInterval(aclogs_interval);
        }
    }, interval);

Though manually triggering interval_en = false; in the browser console will stop it. Still can't find out what went wrong.

Also clicking the pagination buttons before the first interval occur works.

Shiz
  • 695
  • 10
  • 27
  • your first code snippet does not work as `e` is undefined. assuming that was just a copy/paste error, I think the code should work. I would look into the datatable library itself and see if there's a better way to "hook" into their events as any solution with a polling interval is inferior to an event based approach. – Namaskar Jun 04 '21 at 13:00

1 Answers1

1

You could try the following:

    $('#logs_tbl').on( 'page.dt', function () {
        console.log("paginate click");
        $('.btn-live,.btn-notlive').prop('class','btn-notlive');
        interval_en = false;
    } );

This example is reference by datatable site.

aprl11
  • 53
  • 4
  • thanks for this, didn't know that `page.dt`, should have ready the documentation properly. – Shiz Jun 10 '21 at 00:51