【问题标题】:Angular $timeout within loop fails循环内的角度 $timeout 失败
【发布时间】:2016-04-15 12:24:04
【问题描述】:

我使用角度 $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)
 }

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

【问题讨论】:

标签: angularjs timeout


【解决方案1】:

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

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

【讨论】:

    【解决方案2】:

    试试这个

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

    【讨论】:

      猜你喜欢
      • 2016-08-02
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2014-04-29
      • 1970-01-01
      • 1970-01-01
      • 2020-11-01
      • 2016-03-12
      相关资源
      最近更新 更多