Sologoub Sologoub - 1 year ago 102
Javascript Question

Using setInterval() to do simplistic continuos polling

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 endpoint instead of using a proper polling framework?

For the sake of the example, lets say I'm refreshing status of a processing job every 5 seconds.

Answer Source

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);
Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download