Updating the Interval set in real life
This is based on the answer here:
I am having trouble setting setInterval.
The following works are currently in operation. I have a prop called mediaList
that contains an array of image objects. When called changeActiveMedia
, the position of the object is moved to the next one in the list.
class MyComponent extends React.Component {
constructor(props) {
super(props);
this.state = { activeMediaIndex: 0 };
}
componentDidMount() {
setInterval(this.changeActiveMedia.bind(this), 5000);
}
changeActiveMedia() {
const mediaListLength = this.props.mediaList.length;
let nextMediaIndex = this.state.activeMediaIndex + 1;
if(nextMediaIndex >= mediaListLength) {
nextMediaIndex = 0;
}
this.setState({ activeMediaIndex:nextMediaIndex });
}
renderSlideshow(){
const singlePhoto = this.props.mediaList[this.state.activeMediaIndex];
return(
<div>
<img src={singlePhoto.url} />
</div>
);
}
render(){
return(
<div>
{this.renderSlideshow()}
</div>
)
}
}
This is where my problem comes in.
I have a logic that can change the number of items in the list mediaList
.
This becomes a problem because since the interval is only updated every 5000 seconds if nextMediaIndex
at that time is 2 and then I suddenly update the mediaList to only have 1 item, I ran into an error because mediaList [2] does not exist.
So my question is, is there a way to RESET and CLEAR the setInterval whenever it is updated this.props.mediaList
?
source to share
window.setInterval
returns an identifier that identifies the timer Interval
. You can use it in conjunction with clearInterval
to undo the spacing.
this.interval = setInterval(...);
...
clearInterval(this.interval);
you can use it componentWillReceiveProps
as a general check method to see if it has changed mediaList
. eg:
componentWillReceiveProps(nextProps) {
if (nextProps.mediaList !== this.props.mediaList) {
clearInterval(this.interval);
}
}
source to share