Using setInterval() to do simplistic continuous polling

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

    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 second
    poll(() => new Promise(() => console.log('Hello World!')), 1000)
    

提交回复
热议问题