1

AngularJS has a $timeout service which acts as a convenience wrapper around setTimeout.

Why is there no equivalent for setInterval?

Golo Roden
  • 140,679
  • 96
  • 298
  • 425
  • You may find this useful http://stackoverflow.com/questions/14237070/using-setinterval-in-angularjs-factory/14238039#14238039 – zs2020 Aug 19 '13 at 19:22
  • Well, yes and no ;-). It's useful to see how you can implement it, but it does not explain why it is like it is. And this is what my question is about ;-) – Golo Roden Aug 19 '13 at 19:29
  • 1
    I think it's tricky to implement since you will end up with a lot of callback and it is hard to deal with scope.apply. But not for $timeout. $timeout is just a wrapper for `setTimeout()` with calling `scope.apply` at the end of it. So it doesn't make too much sense to implement $interval following the same convention, since you have to call scope.apply periodically, which is expensive. – zs2020 Aug 19 '13 at 19:34
  • 4
    There is: https://github.com/angular/angular.js/commit/2b5ce84fca7b41fca24707e163ec6af84bc12e83 – Cemo Oct 18 '13 at 10:56

1 Answers1

2

Since $timeout is calls scope.apply after each call it can get expensive. However creating a simple interval you can decide what watches and apply calls are needed to keep it clean.

For example, if you interval was running once every minute to check if the user's values had changed and optionally saving it if the values had been changed since the last check. Depending on how you write the code, you may never need to update the web page, so your interval can get by without triggering an update.

That doesn't answer the question directly of why $interval isn't provided by default, but I suspect it is because since it is simple to create your own with you specific requirements, it is better to leave it open for you to enhance, instead of providing a default implementation that is too complex, or too inflexible.

checketts
  • 14,167
  • 10
  • 53
  • 82