Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Using setInterval() to do simplistic continuous polling

For a simple web app 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 an example, let's say I'm refreshing the status of a processing job every 5 seconds.

like image 331
Sologoub Avatar asked Dec 30 '11 18:12

Sologoub


People also ask

Why you should not use setInterval?

In case of time intensive synchronous operations, setTimeInterval may break the rhythm. Also, if any error occurs in setInterval code block, it will not stop execution but keeps on running faulty code. Not to mention they need a clearInterval function to stop it.

Does setInterval affect performance?

The performance of using setInterval will depend on which function you execute each interval.

How do you do a poll in JavaScript?

Polling ImplementationThe executePoll function returns a promise and will run recursively until a stopping condition is met. The poll function takes 4 variables as arguments: fn : This is the function we will execute over a given interval. Typically this will be an API request.

Is setInterval deprecated?

We all know that passing a string to setTimeout (or setInterval ) is evil, because it is run in the global scope, has performance issues, is potentially insecure if you're injecting any parameters, etc. So doing this is definitely deprecated: setTimeout('doSomething(someVar)', 10000);


1 Answers

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); 
like image 53
Felix Kling Avatar answered Oct 02 '22 17:10

Felix Kling