difference between setTimeout in javascript and $timeout service in angularjs

后端 未结 2 719
北恋
北恋 2020-12-05 10:15

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.

2条回答
  •  暖寄归人
    2020-12-05 10:47

    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.

提交回复
热议问题