我正在使用角度$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)
}
但每过一分钟,它就只能安慰"呵呵"。表示它只考虑最后一个值。请让我知道我应该如何获得正确的结果。
今天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)
}
试试这个
$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)
}