Auto Refresh a Html table every x seconds

后端 未结 3 1024
长情又很酷
长情又很酷 2020-12-11 14:22

I am attempting to refresh a table i have as the variables in there are constantly updated and i want to re-update those variable every few seconds. I have already done up c

相关标签:
3条回答
  • 2020-12-11 14:48

    I think setInterval with jQuery.load is the one you're looking for

    var table = $("#tableID");
    
    // refresh every 5 seconds
    var refresher = setInterval(function() {
      table.load("/path/to/js.php");
    }, 5000);
    

    Or shorten it up with

    var refresher = setInterval(table.load.bind(table, "/path/to/data"), 5000);
    

    If you'd ever like to stop refreshing the data, (e.g.,) say the user leaves the page open for a long time

    // stop refreshing after 30 minutes
    setTimeout(function() {
      clearTimeout(refresher);
    }, 1800000);
    

    If your data load takes a while, you might want to only refresh X seconds after the data is loaded. You could do that like this using setTimeout

    var table = $("#tableID");
    
    var refresh = function() {
      table.load("/path/to/js.php", function() {
        setTimeout(refresh, 5000);
      });
    };
    
    refresh();
    
    0 讨论(0)
  • 2020-12-11 14:49

    Just my 2 cents, but this just seems like an unnecessary load to hit your db with. I would consider something like a trigger and write to something less expensive like a

    bool = timestamp > now;
      or
    if(myhash != tablehash)
    

    So your long polling is just asking if something has changed and not running the query

    0 讨论(0)
  • 2020-12-11 14:51

    Change

    $('#tableID').replaceWith($(data)); 
    

    Into

    $('#tableID').replaceWith(data);
    

    Although the thing you do is loading some things into an element. So semantically speaking using .load() sounds better.

    $('#tableID').load('some/url/file.php')
    
    0 讨论(0)
提交回复
热议问题