2016-04-15 69 views
3

我採用了棱角分明$超時的,

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

但每一分鐘後,只允許進行控制檯「嘿嘿」。意味着它只考慮最後的價值。請讓我知道我應該如何得到適當的結果。

+0

請看看下面的,如果想要一些解釋http://stackoverflow.com/questions/5226285/settimeout-in-for-loop-does-not-print-連續值?lq = 1,http://stackoverflow.com/questions/750486/javascript-closure-inside-loops-simple-practical-example – koox00

回答

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

它的工作原理。謝謝:) – Priyanka

+0

@Priyanka:很酷..謝謝 – Thalaivar

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