Skip to content Skip to sidebar Skip to footer

Set Timeout To React Function

I have the following object list: mediaList[ {id:1, url:'www.example.com/image1', adType:'image/jpeg'}, {id:2, url:'www.example.com/image2', adType:'image/jpg'}, {id:3, url:'www

Solution 1:

If you want to change the media on every 5 seconds, you will have to update the state to re-render your components You can also use setInterval instead of setTimeout. setTimeout will be triggered only once, setInterval will be triggered every X milliseconds. Here what it may look like:

classMyComponentextendsReact.Component {
  constructor(props) {
    super(props);
    this.state = { activeMediaIndex: 0 };
  }

  componentDidMount() {
    setInterval(this.changeActiveMedia.bind(this), 5000);
  }

  changeActiveMedia() {
    const mediaListLength = this.props.medias.length;
    let nextMediaIndex = this.state.activeMediaIndex + 1;

    if(nextMediaIndex >= mediaListLength) {
      nextMediaIndex = 0;
    }

    this.setState({ activeMediaIndex:nextMediaIndex });
  }

  renderSlideshow(){
    const ad = this.props.medias[this.state.activeMediaIndex];
    let adType = ad.adType;
    if(type.includes("image")){
      return(
        <divclassName="imagePreview"><imgsrc={ad.url} /></div>
      );
    }elseif (adType.includes("video")){
      return(
        <videoclassName="videoPreview"controls><sourcesrc={ad.url}type={adType}/>
          Your browser does not support the video tag.
        </video>
      )

    }
  }

  render(){   
    return(
      <div>
          {this.renderSlideshow()}
      </div>
    )
  }
}

Basically what the code is doing is that every 5 seconds, will change the activeMediaIndex to the next one. By updating the state, you will trigger a re-render. When rendering the media, just render one media (you can also render the previous one and the next one like a classic slideshow). Thus way, every 5 seconds, you will render a new media.

Solution 2:

Don't forget to clear the timeout to prevent memory leaks:

componentDidMount() {
    this.timeout = setTimeout(() => {
     ...
    }, 300);
  }

  componentWillUnmount() {
    clearTimeout(this.timeout);
  }

Post a Comment for "Set Timeout To React Function"