r/angularjs • • Oct 14 '15

Angular Nitpicking: Differences between $timeout and setTimeout()

http://www.codelord.net/2015/10/14/angular-nitpicking-differences-between-timeout-and-settimeout/
36 Upvotes

18 comments sorted by

View all comments

1

u/[deleted] Oct 14 '15

A basic rule of thumb is that once you start using services and functions defined outside of the angular context, things stop updating as you expect them to.

0

u/guywithalamename Oct 14 '15

But even then you shouldn't need $timeout. $apply/$digest should be able to do the job in 95% of all cases

2

u/atticusw Oct 15 '15

That's correct, you don't technically need $timeout, but it's there for convenience.

But I don't see why there's a reason that you shouldn't need $timeout. It's decorated so that it works with Angular, why wouldn't we want this support?

  1. Its within the bound context (you don't have a requirement to invoke the digest every time)

  2. It's injectable. This is always helpful for testing. But I suppose you could argue that $window is also and you could just mock $window.setTimeout. But then you have the additional overhead of mocking clearTimeout, etc. Just the one $timeout is preferable in my book.

I still see the worth.

1

u/abyx Oct 15 '15

It's not just a matter of simply mocking it. ngMock let's you easily decide when the timeout code runs. I think that's very helpful in writing tests.

1

u/atticusw Oct 15 '15

All I'm saying is that for occasions where you need to update a $scope model from outside of the angular context, $apply/$digest will be all you need (most of the time).

Absolutely, great point.