消耗更少资源的 setInterval 替代方案

Fel*_*ger 0 javascript setinterval reactjs

我有一个每 4 秒更改一次图像的组件,如下所示:

state = {
  images: this.props.items,
  imageIndex: 0,
}
componentDidMount() {
  this.interval = setInterval(() => this.changeImage(), 4000)
}
changeImage = () => {
  const { imageIndex, images } = this.state
  if (imageIndex === images.length - 1) {
    this.setState({ imageIndex: 0 })
  } else {
    this.setState({ imageIndex: imageIndex + 1 })
  }
}
render() {
  const { images, imageIndex } = this.state
  return <img src={images[imageIndex]} />
}
Run Code Online (Sandbox Code Playgroud)

该组件在页面上的 6 个位置使用。

问题是几分钟后,风扇继续运转,计算机变热。我不知道这是由于CPU使用量增加还是内存泄漏造成的。

是否有任何替代方法setInterval(以预定义的时间间隔执行重复的任务),同时使用更少的计算机资源?

pgs*_*rom 5

setInterval用于此目的并没有本质上的错误。但您应该确保在卸载组件时清除间隔!clearInterval为此目的调用了一个函数。这很可能是性能问题的根源。

所以我建议这样:

componentWillUnmount() {
  clearInterval(this.interval);
}
Run Code Online (Sandbox Code Playgroud)