Fellow Stranger
Fellow Stranger

Reputation: 34043

Alternative to setInterval that consumes less resources

I have a component that changes images every 4 seconds like this:

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]} />
}

The component is used in 6 spots on the page.

The problem is that after a couple of minutes, the fan goes on and the computer gets warm. I don't know if this is caused by increased CPU usage or memory leaks.

Is there any alternative method to setInterval (execute a repeated task at a predefined interval), while using less computer resources?

Upvotes: 0

Views: 2837

Answers (2)

pgsandstrom
pgsandstrom

Reputation: 14399

There is nothing inherently wrong with using setInterval for this purpose. But you should make sure that you clear the interval when the component is unmounted! There is a function called clearInterval for this purpose. This could very well be the source of your performance issues.

So I suggest something like this:

componentWillUnmount() {
  clearInterval(this.interval);
}

Upvotes: 5

Vikasdeep Singh
Vikasdeep Singh

Reputation: 21766

Try with setTimeout:

function myFn() {
  setTimeout(myFn, 4000);
}
myFn();

Upvotes: 0

Related Questions