javascript - React——为什么循环状态更新先于递归状态更新?

标签 javascript reactjs loops iteration

当您单击开始按钮时,它会启动两个计数器。一种使用递归,另一种使用 for 循环。为什么循环计数器会阻塞递归计数器的计数?另外,为什么for循环中的迭代次数有限制?

import React from 'react'
export default class Clock extends React.Component {

state = {
    recursiveCount: 0,
    loopCount: 0,
    stop: false
  }

  clickStart = () => {
      this.setState({
      stop: false
}, () => {
      this.startRecursion()
      this.startLooping()
     })
  }

   startLooping = () => {
       for (let i = 0; i < 1000; i++) {
       setTimeout(() => {
            this.setState({
           loopCount: this.state.loopCount + 1
      })
  }, 1)
    }
  }

   stop = () => {
     this.setState({
     stop: true
})
  }

  startRecursion = () => {
        if (!this.state.stop) {
        setTimeout(() => {
        this.setState({
          recursiveCount: this.state.recursiveCount + 1
        }, () => {
          this.startRecursion()
       })
      }, 1)
    }
  }

  render () {
    return (
     <div>
     <button className = 'button' onClick = 
 {this.clickStart}>Start</button>
     <button className = 'button' id = 'stop' onClick = 
{this.stop}>Stop</button>
     <h1>The recursive function has been recursively called {this.state.recursiveCount} times</h1>
  <h1> The iterative function has been iteratively called {this.state.loopCount} times </h1>
 </div>
)
  }


 }

最佳答案

让我们单步执行代码:

  for (let i = 0; i < 1000; i++) {

循环1000次。就这么多,可能会让浏览器挂起一段时间。

 setTimeout(/*callback*/, 1);

您向队列添加了大量超时。现在代码已经完成了。一滴答之后,所有超时同时触发,并且将直接依次执行。这就是为什么计数器直接从 1000 跳到 2000。

Why does the looping counter block the counting of the recursive counter?

因为只有一个线程,并且该线程将被同时进入线程队列的 1000 个回调阻塞。递归超时也会在队列中结束,因此只会在其他 1000 个之后执行,这需要时间。

Also, why is there a limit for the number of iterations in the for loop?

循环中没有数量限制,但是如果您阻塞线程太长时间,它就会崩溃以帮助客户端:

 while(true );

此外,正如 chris 指出的那样,在循环中过于频繁地调用 setState 可能会给您带来麻烦。

关于javascript - React——为什么循环状态更新先于递归状态更新?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/51937977/

相关文章:

css - 使用 Button React 更改 .scss

javascript - ReactJS:如何在同一网站上拥有多个 SPA

java - 使用 Java - 每 9 个字符宽行打印四次迭代

c - 仅通过 EOF 结束 while 循环一次

javascript - 在网络音频中,为什么 contextTime 比 baseLatency 滞后 currentTime?

javascript - 从 JQuery Widget 返回一个值

javascript - typescript 错误 - 属性 'headers' 的类型不兼容

javascript - 光滑 slider 人为居中

javascript - Reactjs @setState 具有动态键值

c++ - C++ 中循环的替代方案