Using setInterval() to do simplistic continuous polling

后端 未结 5 631
孤街浪徒
孤街浪徒 2020-12-13 03:45

For a simple webapp that needs to refresh parts of data presented to the user in set intervals, are there any downsides to just using setInterval() to get a JSON from an end

5条回答
  •  离开以前
    2020-12-13 04:22

    From my comment:

    I would use setTimeout [docs] and always call it when the previous response was received. This way you avoid possible congestion or function stacking or whatever you want to call it, in case a request/response takes longer than your interval.

    So something like this:

    function refresh() {
        // make Ajax call here, inside the callback call:
        setTimeout(refresh, 5000);
        // ...
    }
    
    // initial call, or just call refresh directly
    setTimeout(refresh, 5000);
    

提交回复
热议问题