小编典典

在AngularJS中使用$ timeout而不是window.setTimeout有什么优势?

angularjs

我建议实施这样的超时:

  $timeout(function() {

    // Loadind done here - Show message for 3 more seconds.
    $timeout(function() {
      $scope.showMessage = false;
    }, 3000);

  }, 2000);
};

有人可以告诉我使用此方法而不使用setTimeout的原因/优势是什么?


阅读 369

收藏
2020-07-04

共1个答案

小编典典

用基本的话$timeout指的是angularjs when-指setTimeoutJavaScript。

如果您仍然认为要使用setTimeout,则需要$scope.$apply()在之后调用

示例1:$ timeout

   $scope.timeInMs = 0;

    var countUp = function() {
        $scope.timeInMs+= 500;
        $timeout(countUp, 500);
    }    
    $timeout(countUp, 500);

示例2:setTimeout(相同的逻辑)

 $scope.timeInMs_old = 0;

    var countUp_old = function() {
        $scope.timeInMs_old+= 500;        
        setTimeout(function () {
        $scope.$apply(countUp_old);
    }, 500);
    }

    setTimeout(function () {
        $scope.$apply(countUp_old);
    }, 500);

演示版 **[Fiddle](http://jsfiddle.net/fq4vg/206/)**


$超时也返回一个承诺

JS

function promiseCtrl($scope, $timeout) { 
 $scope.result = $timeout(function({ 
 return "Ready!"; 
 }, 1000); 
}

HTML

<div ng-controller="promiseCtrl"> 
 {{result || "Preparing…"}}
</div>

$超时也会触发摘要周期

考虑我们有一些3d派对代码(不是AngularJS),例如Cloudinary插件,它上传一些文件并返回“进度”百分比率回调。

     // .....
     .on("cloudinaryprogress",
           function (e, data) {
               var name = data.files[0].name;
               var file_ = $scope.file || {};
               file_.progress = Math.round((data.loaded * 100.0) / data.total);


                $timeout(function(){
                     $scope.file = file_;
                }, 0);         
            })

我们想更新我们的UI $scope.file = file_;

因此,为我们 做空 $timeout的工作将触发摘要周期,$scope.file并由3d party更新后将在GUI中重新渲染

2020-07-04