AngularJS polling service

A while ago, I had to write a polling service in AngularJS. For this service, there were three main requirements:

  1. poll the backend every x ms until the expected result has been attained
  2. the service has to timeout after a set period of time
  3. one should be able to stop the polling


The polling and the timeout were fairly trivial to implement. There was only one gotcha. If you’re using Protractor for e2e testing, you have to use $interval instead of $timeout. Protractor has issues figuring out when AngularJS is done with its work when you use $timeout. With the $interval service it behaves like expected.

The tricky part for me turned out to be the third requirement. How do you cancel the polling? Eventually, I figured out that it had to be done through cancelling the $interval/$timeout.

To summarise, here is an example that outlines what I’ve come up with: