Using setInterval() to do simplistic continuous polling

后端 未结 5 632
孤街浪徒
孤街浪徒 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:27

    I know this is an old question but I stumbled over it, and in the StackOverflow way of doing things I thought I might improve it. You might want to consider a solution similar to what's described here which is known as long polling. OR another solution is WebSockets (one of the better implementations of websockets with the primary objective of working on all browsers) socket.io.

    The first solution is basically summarized as you send a single AJAX request and wait for a response before sending an additional one, then once the response has been delivered, queue up the next query.

    Meanwhile, on the backend you don't return a response until the status changes. So, in your scenario, you would utilize a while loop that would continue until the status changed, then return the changed status to the page. I really like this solution. As the answer linked above indicates, this is what facebook does (or at least has done in the past).

    socket.io is basically the jQuery of Websockets, so that whichever browser your users are in you can establish a socket connection that can push data to the page (without polling at all). This is closer to a Blackberry's instant notifications, which - if you're going for instant, it's the best solution.

提交回复
热议问题