我正在尝试创建一个 FOR 循环,该循环每 1000 毫秒删除一个元素,而不是立即通过数组并执行操作。
我这样做是出于性能原因,因为正常情况下通过循环会卡住我的 UI。
function removeFunction (i,selected) {
selected[i].remove();
}
function startLoop() {
var selected = paper.project.selectedItems;
for (var i = 0; i < selected.length; i++) {
if (selected[i].name === "boundingBoxRect") continue;
setTimeout(removeFunction(i,selected),1000)
}
}
似乎 selected[i].remove() 方法被立即调用。这是为什么?由于我已将超时设置为 1000 毫秒,难道不应该以 1000 毫秒的间隔删除这些项目吗?
注意
在上面的代码中,我跳过了一个名为 boundingBoxRect 的项目,因为我不想删除它。只是说明这一点,以免造成混淆
最佳答案
简单的把它变成一个递归函数:
function removeFunction (i, selected) {
// If i is equal to the array length, prevent further execution
if (i === selected.length)
return;
// Remove ith child of selected array
selected[i].remove();
// Trigger same function after 1 second, incrementing i
setTimeout(function() {
removeFunction(++i,selected)
}, 1000);
}
// Trigger the function to begin with, passing in 0 as i
removeFunction(0, paper.project.selectedItems);
这是一个 JSFiddle demo (使用 console.log
而不是 selected[i].remove()
,因为您尚未提供该函数的定义);
关于javascript - 延迟 For 循环,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/23894185/