angularjs - 循环内的 Angular $timeout 失败

标签 angularjs timeout

我使用 Angular $timeout作为,

 $scope.alltexts = ["hii" , "hello" , "hehe"]
 var sendtime = 60000

 for (var i = 0; i < $scope.alltexts.length; i++) {
   var text = $scope.alltexts[i]
   $setTimeout(function() {}, (function(){$scope.addtext(text)}, sendtime + (i * 60000)));
 };

 $scope.addtext = function(text){
  console.log(text)
 }

但是每一分钟之后它只会安慰“呵呵”。意味着它只考虑最后一个值。请让我知道我应该如何获得正确的结果。

最佳答案

今天的闭包太多了,你总是传递最后一个索引...闭包将为每次迭代创建一个新的范围

 $scope.alltexts = ["hii" , "hello" , "hehe"]
 var sendtime = 60000

 for (var i = 0; i < $scope.alltexts.length; i++) {
   (function(i){
   var text = $scope.alltexts[i]
   $setTimeout(function() {}, (function(){$scope.addtext(text)}, sendtime + (i * 60000)));
   })(i)
 };

 $scope.addtext = function(text){
  console.log(text)
 }

关于angularjs - 循环内的 Angular $timeout 失败,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/36647102/

相关文章:

c++ - 使用 Boost datetime 在 C++ 中超时

javascript - AngularJS 摘录函数

HTTP 保活超时

mysql - 防止 Mongrel/Mysql Errno::EPIPE 异常

javascript - AngularJS $scope 下降

cuda - 启动 CUDA-Kernel 并设置超时

mysql - WordPress - MySQL 服务器已经消失

angularjs - 在文本区域中插入制表符

javascript - ng 重复 json 解析显示空字符串

javascript - 工厂方法引用混淆,以及编码指南