javascript - 为什么下面的代码没有针对 for 循环中 i 的每个值执行?
问题描述
SetTimeout不适用于 for 循环的每个 i。我已经尝试了几乎所有东西,使用过承诺等,但没有任何效果。
animateDijkstra(visitedNodesInOrder) {
for (let i = 0; i < visitedNodesInOrder.length; i++) {
// here set timeout is not working for each i :(
setTimeout(() => {
const node = visitedNodesInOrder[i];
const newGrid = this.state.grid.slice();
const newNode = {
...node,
isVisited: true,
};
newGrid[node.row][node.col] = newNode;
this.setState({ grid: newGrid });
}, 3000 * (i + 1));
}
};
解决方案
animateDijkstra(visitedNodesInOrder) {
for (let i = 0; i < visitedNodesInOrder.length; i++) {
// here set timeout is not working for each i :(
(function() {
setTimeout(() => {
const loopVariable = i;
const node = visitedNodesInOrder[loopVariable];
const newGrid = this.state.grid.slice();
const newNode = {
...node,
isVisited: true,
};
newGrid[node.row][node.col] = newNode;
this.setState({
grid: newGrid
});
}, 3000 * (loopVariable + 1));
})()
}
};
推荐阅读
- python-3.x - 通过 Python 中的 Databricks api 读取 Databricks 表?
- python - 如何确定熊猫数据框中的值是否也存在于前一个日期?
- .net-4.0 - Windows 模拟 - 负载均衡器
- powershell - 如何使用 Powershell 在 AD 中提取管理器的多个属性?
- file - 在 Ansible 中打印时保留文件的格式
- node.js - Google Code Jam:我对火车时刻表问题的解决方案失败了
- swiftui - SwiftUI TabView 索引视图不尊重页面视图索引
- mongodb - 使用来自 mongodb 触发器的 cloudwatch 事件触发 aws lambda 函数比使用 sqs 中的消息有多可靠?
- postgresql - 错误:Docker-compose Postgres 中“CREATE”或附近的语法错误
- firebase - Flutter Web Firebase 错误。未捕获的 ReferenceError:未定义 firebase