Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
1.0k views
in Technique[技术] by (71.8m points)

difference between setTimeout in javascript and $timeout service in angularjs

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

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

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

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

Why we should use $timeout instead of setTimeout??

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

Thanks :)

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

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

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 provides a handy wrapper for this: $timeout() - it does the $apply() for which we don't have to $apply the changes.

Regarding the performance.

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.


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...