Search code examples
angularjsangularjs-timeout

What's the difference between $evalAsync and $timeout in AngularJS?


I've been using AngularJS for a little while now, and have found the need to use $timeout every once in a while (Seems to usually be to init a jQuery plugin).

Recently, I've been trying to get a better and more in-depth understanding of the digest cycle, and I came across $evalAsync function.

It seems like that function produces similar results to $timeout, only you don't give it delay. Every time I've used $timeout it has been with a delay of 0, so now I'm wondering if I should have used $evalAsync instead.

Are there any fundamental differences between the two? What cases would you use one over the other? I'd like to get a better feeling of when to use which one.


Solution

  • I recently answered essentially this question here: https://stackoverflow.com/a/17239084/215945 (That answer links to some github exchanges with Misko.)

    To summarize:

    • if code is queued using $evalAsync from a directive, it should run after the DOM has been manipulated by Angular, but before the browser renders
    • if code is queued using $evalAsync from a controller, it should run before the DOM has been manipulated by Angular (and before the browser renders) -- rarely do you want this
    • if code is queued using $timeout, it should run after the DOM has been manipulated by Angular, and after the browser renders (which may cause flicker in some cases)