Why would I use RxJS interval() or timer() polling instead of window.setInterval()? Why would I use RxJS interval() or timer() polling instead of window.setInterval()? typescript typescript

Why would I use RxJS interval() or timer() polling instead of window.setInterval()?


Advantage of RxJS:

Laziness

You can create your Observables and until you call subscribe nothing is happening. Observable = pure function. This gives you more control, easier reasoning and allows for next point...

Composability

You can combine interval/timer with other operators creating custom logic very easily in unified way - for example you can map, repeat, retry, take... etc. see all operators

Error Handling

In case of an error you are responsible for calling clearTimeout/clearInterval - Observables are handling this for you. Resulting in cleaner code and fewer memory leak bugs.

Of course anything you do with Observables you can also do without Observables - but that's not the point. Observables are here to make your life easier.


Also note that interval/timer are not good observable factories for polling because they do not "wait" for your async action to finish (you can end up with multiple async calls running over each other). For that I tend to use defer and repeatWhen like this:

defer(() => doAsyncAction())  .pipe(    repeatWhen(notifications => notifications.pipe(delay(1234)))  );


window.setInterval doesn't care about your callbacks state, it'll execute at the given interval despite the status of the execution of the past callback, and the only way to make it stop and skip is clear the interval or reinitialize it.

On the other hand, RxJS Observable based solutions(interval, timer) allow you to pipe conditional operators (takeWhile, skipWhile for example) which allows you to add a stop or implement a stop-start logic by just flipping a boolean flag, instead of adding complicated logic of clearing the interval, and then recreating it.

And they are observables, you can listen to them all across the application, and attach any number of listeners to it.

Error Handling is better too, you subscribe to all successes, and handle everything in a catch callback.