javascript中的setTimeout与angularjs中的$ timeout服务之间的差异 [英] difference between setTimeout in javascript and $timeout service in angularjs

查看:126
本文介绍了javascript中的setTimeout与angularjs中的$ timeout服务之间的差异的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我是角度框架的新手。这是我的场景,我想在一段时间后更改我的$ scope.variable所以我使用javascript setTimeout 方法。

Iam new to angular framework.Here is my scenario where, I want to change my $scope.variable after a period of time so i used javascript setTimeout method.

$scope.variable='Previous';

setTimeout(function(){
$scope.variable='NEXT';
},3000);

此代码对我不起作用。我使用 $ apply()来使这段代码工作。

This code doesn't worked for me. I used $apply() to make this code work.

后来我才知道角度本身有一个$ timeout服务执行相同的工作。

Later i came to know that angular itself has a $timeout service which does the same work.

$scope.variable='Previous';
        $timeout(function () {
            $scope.variable='NEXT';
    }, 2000);

如何比较 $ timeout 的性能?使用javascript服务 setTimeout ??

How can i compare performance of $timeout service with javascript setTimeout??

为什么我们应该使用 $ timeout 而不是 setTimeout ??

Why we should use $timeout instead of setTimeout??

请给我一些使用它的例子和理由,其中显示了性能。

Please give me some examples and reasons to use it, which shows the performance.

谢谢:)

推荐答案

在某些情况下一个人需要执行某种超时操作,我们经常使用JavaScript的 setTimeout()函数来实现这一点。

There are some cases where one needs to perform some sort of timeout operation and we frequently achieve this using JavaScript's setTimeout() function.

但是,如果我们在AngularJS应用程序中使用 setTimeout(),我们还需要使用 $ scope。$ apply()来确保对范围的任何更改都将反映在其他位置(即视图中的数据绑定)。

However, if we use setTimeout() in an AngularJS application we also need to use $scope.$apply() to ensure that any changes to the scope will be reflected elsewhere (i.e. data-bound in a view).

AngularJS 为此提供了一个方便的包装: $ timeout() - 它执行 $ apply()我们没有必须 $ apply 更改。

AngularJS provides a handy wrapper for this: $timeout() - it does the $apply() for which we don't have to $apply the changes.

关于效果

如果您使用 $ timeout 来创建本质上是间隔的内容,则不要使用它。如果您的应用程序很大,那么 $ apply 也会触发 $ digest 循环,您可能不希望它发生,肯定会降低性能。

If you're using $timeout to create what is essentially an interval, then don't use it. If your application is large then $apply will also trigger a $digest cycle which you may not really want it to happen, it will surely decrease the performance.

这篇关于javascript中的setTimeout与angularjs中的$ timeout服务之间的差异的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆