我遇到了一个问题,我设置了一堆超时调用,我希望超时函数能够引用当前循环中的元素。
这就是结果:
var createTimedMessages = function(arr, collection){
var timeLimit = 2000;
for(var i = 0; i<arr.length; i++){
let el = arr[i];
collection.push(el);
$timeout(function removeElement(){
collection.removeMatch(el);
}, timeLimit);
}
}
但我意识到由于缺少对let关键字的支持,这对于一些稍微旧的浏览器不起作用。什么是好的解决方法?
注意:这是有角度的,因此是$ timeout而不是setTimeout。
答案 0 :(得分:4)
使用IIFE:
var createTimedMessages = function(arr, collection) {
var timeLimit = 2000;
for (var i = 0; i < arr.length; i++) {
(function(el) {
collection.push(el);
$timeout(function removeElement() {
collection.removeMatch(el);
}, timeLimit);
})(arr[i]);
}
}
答案 1 :(得分:0)
自动执行功能应解决问题:
(function(el, timeLimit) {
$timeout(/* your code */);
})(arr[i], timeLimit);