首页 > 解决方案 > 为什么下面的代码没有针对 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));
  }
};

标签: javascriptreactjses6-class

解决方案


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

推荐阅读