If i need to get some new data constanly, i know that best solution is websockets.In that way the server will notify the client when there is new data. But to avoid this just for one scenario, i will need to call some http request on every five seconds.
I am using here counter just for simulation instead calling some http service.
let counter = 0;
setInterval(() => {
console.log(counter);
++counter;
},5000)
I've read that better solution is requestAnimationFrame instead of setInterval.It is more optimised by the browser and also when the tab is not active it is paused. Set interval continues to fire and when the tab is not active which is not good.
How can i call some function in requestAnimationFrame every five seconds ?
To actually only call it every 5 seconds, you'd still need (at least) setTimeout
. But with this, something along the following would work:
requestAnimationFrame(function run() {
console.log('do something w/o initial delay');
setTimeout(function () {
console.log('do something w/ initial delay');
requestAnimationFrame(run);
}, 5000);
});