在AngularJS中使用$ timeout而不是window.setTimeout有什么优势? [英] What advantage is there in using the $timeout in AngularJS instead of window.setTimeout?

查看:84
本文介绍了在AngularJS中使用$ timeout而不是window.setTimeout有什么优势?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我建议实施这样的超时:

I had a suggestion to implement a timeout like this:

  $timeout(function() {

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

  }, 2000);
};

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

Can someone tell me what is the reason / advantage in using this rather than using setTimeout?

推荐答案

用基本词$timeoutsetTimeout时指的是angularjs-到JavaScript.

In basic words $timeout refers to angularjs when setTimeout - to JavaScript.

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

If you still think to use setTimeout therefore you need invoke $scope.$apply() after

作为旁注

我建议您阅读 发布

I suggest you to read How do I "think in AngularJS" if I have a jQuery background? post

AngularJS:使用$ timeout,而不是setTimeout

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

演示 小提琴

JS

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

HTML

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


$ timeout也会触发摘要周期

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


$timeout also trigger digest cycle

Consider we have some 3d party code (not AngularJS) like Cloudinary plugin that uploads some file and returns us 'progress' percentage rate callback.

     // .....
     .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);         
            })

我们要更新我们的用户界面,又称为 $scope.file = file_;

We want to update our UI aka $scope.file = file_;

因此 empty $timeout为我们完成了工作,它将触发摘要周期,并且3d方更新的$scope.file将在GUI中重新呈现

So empty $timeout does the job for us, it will trigger digest cycle and $scope.file updated by 3d party will be re-rendered in GUI

这篇关于在AngularJS中使用$ timeout而不是window.setTimeout有什么优势?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆