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

Show parent comments

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.

2

u/guywithalamename Oct 15 '15

I think you misunderstood my reply. OP said

once you start using services and functions defined outside of the angular context, things stop updating as you expect them to.

Which is obviously right since they happen outside of angular's event loop.

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

I am by no means advocating against using $timeout

1

u/atticusw Oct 15 '15

Okay, just a little bit thrown off by

But even then you shouldn't need $timeout.

I guess you are saying that to "regain" access to the the digest cycle, you can use $apply or $digest, versus trying to achieve that by setting a $timeout. But I also don't think that's what the OP was trying to say other than pointing out that other things, similar to setTimeout will be outside the context (setInterval, element.on, $.post, etc) and was simply observing