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

Sam*_*tar 50 settimeout angularjs

我有一个建议实现这样的超时:

  $timeout(function() {

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

  }, 2000);
};
Run Code Online (Sandbox Code Playgroud)

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

Max*_*tin 64

在基本的单词$timeout中指的是angularjs setTimeout- 对于JavaScript.

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

作为旁注

我建议你阅读How do I "think in AngularJS" if I have a jQuery background?帖子

AngularJS: use $timeout, not setTimeout

示例1:$ timeout

   $scope.timeInMs = 0;

    var countUp = function() {
        $scope.timeInMs+= 500;
        $timeout(countUp, 500);
    }    
    $timeout(countUp, 500); 
Run Code Online (Sandbox Code Playgroud)

示例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);
Run Code Online (Sandbox Code Playgroud)

演示 Fiddle


$ timeout也返回一个promise

JS

function promiseCtrl($scope, $timeout) { 
 $scope.result = $timeout(function({ 
 return "Ready!"; 
 }, 1000); 
}
Run Code Online (Sandbox Code Playgroud)

HTML

<div ng-controller="promiseCtrl"> 
 {{result || "Preparing…"}}
</div> 
Run Code Online (Sandbox Code Playgroud)

$ timeout也会触发摘要周期

考虑我们有一些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);         
            })
Run Code Online (Sandbox Code Playgroud)

我们想要更新我们的用户界面 $scope.file = file_;

如此空白 $timeout为我们完成工作,它将触发摘要周期$scope.file并由3d方更新将在GUI中重新呈现

  • `setTimeout()`绝对不是指jQuery(它的标准JavaScript). (32认同)
  • 是的,抱歉,我忘了上次使用`setTimeout`时.谢谢你的解决 (3认同)
  • $ timeout也返回一个promise:该示例似乎非常有用! (3认同)

ksi*_*ons 20

  1. 它会在try/catch块中自动包装你的回调,让你在$ exceptionHandler服务中处理错误:http://docs.angularjs.org/api/ng.$exceptionHandler
  2. 它返回一个promise,因此与传统的回调方法相比,它可以更好地与其他基于promise的代码进行互操作.回调返回时,返回的值用于解析promise.