javascript 中的 setTimeout 和 angularjs 中的 $timeout 服务之间的区别 [英] difference between setTimeout in javascript and $timeout service in angularjs

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

问题描述

我是 Angular 框架的新手.这是我的场景,我想在一段时间后更改 $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 work for me. I used $apply() to make this code work.

后来我知道 angular 本身有一个 $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() 来确保对 scope 将反映在其他地方(即 view 中的数据绑定).

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天全站免登陆