栏目分类:
子分类:
返回
名师互学网用户登录
快速导航关闭
当前搜索
当前分类
子分类
实用工具
热门搜索
名师互学网 > IT > 面试经验 > 面试问答

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

面试问答 更新时间: 发布时间: IT归档 最新发布 模块sitemap 名妆网 法律咨询 聚返吧 英语巴士网 伯小乐 网商动力

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

用基本的话

$timeout
指的是angularjs when-指
setTimeout
Javascript。

如果您仍然认为要使用

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中重新渲染



转载请注明:文章转载自 www.mshxw.com
本文地址:https://www.mshxw.com/it/367508.html
我们一直用心在做
关于我们 文章归档 网站地图 联系我们

版权所有 (c)2021-2022 MSHXW.COM

ICP备案号:晋ICP备2021003244-6号