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)))
  );

Leave a Comment

Hata!: SQLSTATE[HY000] [1045] Access denied for user 'divattrend_liink'@'localhost' (using password: YES)