循环中的Angular $ timeout失败

时间:2016-04-15 12:24:05

标签: angularjs timeout

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

但每一分钟之后它只能安慰“呵呵”。意味着它只考虑最后一个值。请告诉我如何获得正确的结果。

2 个答案:

答案 0 :(得分:2)

今天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)
 }

答案 1 :(得分:1)

试试这个

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