Using setInterval() to do simplistic continuous polling Using setInterval() to do simplistic continuous polling ajax ajax

Using setInterval() to do simplistic continuous polling


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 directlysetTimeout(refresh, 5000);


A simple non-blocking poll function can be implemented in recent browsers using Promises:

var sleep = time => new Promise(resolve => setTimeout(resolve, time))var poll = (promiseFn, time) => promiseFn().then(             sleep(time).then(() => poll(promiseFn, time)))// Greet the World every secondpoll(() => new Promise(() => console.log('Hello World!')), 1000)


You can do just like this:

var i = 0, loop_length = 50, loop_speed = 100;function loop(){    i+= 1;     /* Here is your code. Balabala...*/    if (i===loop_length) clearInterval(handler);}var handler = setInterval(loop, loop_speed);