问题描述
我已经使用 AngularJS 一段时间了,发现需要使用 $timeout 每隔一段时间(似乎通常是初始化一个 jQuery 插件).
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).
最近,我一直在尝试对摘要循环有更好更深入的了解,我遇到了 $evalAsync 函数.
Recently, I've been trying to get a better and more in-depth understanding of the digest cycle, and I came across $evalAsync function.
似乎该函数产生的结果与 $timeout
类似,只是您不给它延迟.每次我使用 $timeout
时,它的延迟都是 0,所以现在我想知道我是否应该使用 $evalAsync
代替.
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.
推荐答案
我最近在这里回答了这个问题:https://stackoverflow.com/a/17239084/215945(该答案链接到与 Misko 的一些 github 交流.)
I recently answered essentially this question here: https://stackoverflow.com/a/17239084/215945(That answer links to some github exchanges with Misko.)
总结:
- 如果代码使用指令中的$evalAsync 排队,它应该在 DOM 被 Angular 操作之后运行,但之前浏览器渲染
- 如果代码使用控制器中的 $evalAsync 进行排队,它应该在 DOM 被 Angular 操作之前运行(并且在浏览器呈现之前)——很少这样做你想要这个
- 如果代码使用 $timeout 排队,它应该在 DOM 被 Angular 操作之后运行,并且在浏览器呈现(在某些情况下可能会导致闪烁)
- 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)
这篇关于AngularJS 中的 $evalAsync 和 $timeout 有什么区别?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!