0

JS setInterval vs async Ajax / websocket

I came across the very handy JS setInterval function which refreshes a value from the DOM in-place. Quite useful. Trying to analyze pros / cons of leveraging this to fetch data from a remote API to be updated on the rendered page vs Websockets to do the same thing. I like the abstraction setInterval provides, its clear what its doing. On the flip side, I like the bidirectional and “push” based nature of websockets, removing the need to poll/query at predetermined intervals. However, I’m seeking for others opinion on this matter for production use cases. Debugging code, modifying it months after, etc. Assume the value needs to be refreshed in place every few seconds (not real time). What would you suggest? Thanks

28th Apr 2019, 7:26 PM
pinga Lola
pinga Lola - avatar
3 Antworten
0
In my opinion setInterval is not as reliable as a callback is. If the client is slow/has a lag/network connection is not good it can overlap or skip steps. Ajax-call that repeats itself on success, optionally with setTimeout is the solution of my choice.
28th Apr 2019, 8:28 PM
spotbot2k
spotbot2k - avatar
0
so implementation wise, would you suggest running a loop, either infinite or broken out of based on other state from DOM, which does the ajax call / updates DOM, and “sleeps” for N seconds? i guess the part im missing here is how to go about “scheduling” my ajax calls. what i liked about the setinterval was this - the “scheduler” like support. perhaps i can trigger the ajax based on some sort of timer event (im assuming such event exists) to avoid having to deal with the loop/sleeping/yielding.
28th Apr 2019, 9:32 PM
pinga Lola
pinga Lola - avatar
0
No, not a loop. I'm talking about recursion. Starting point is window.load and then repeat itself. The "timer" is window.setTimeout.
29th Apr 2019, 8:40 PM
spotbot2k
spotbot2k - avatar