Home > Software engineering >  React setState in setInterval not updated immediately
React setState in setInterval not updated immediately

Time:03-20

I was working on a slideshow component and I would like to update its interval for auto-playing. But, the value is not immediately updated. Whenever I click to speed up or slow down, the state is using the value in the last time, not the one updated even I used setState().

var id;
const data = [img1, img2, img3, img4];

class Slideshow extends React.Component {
    constructor(props) {
        super(props);
        this.state = { ImgId: 0, interval: 2000 };
    }
    startSlideshow() {
        this.pause(); // prevent start multiple setInterval()
        id = setInterval(() => {
            this.setState(state => ({...state, ImgId: (state.ImgId   1) % data.length}))
        }, this.state.interval);
        console.log(this.state.interval);
    }
    pause() {
        if (id) {
            clearInterval(id);
        }
    }
    slowDown() {
        this.setState((state) => ({...state, interval: state.interval   250}));
        this.startSlideshow();
    }
    speedUp() {
        this.setState((state) => ({...state, interval: state.interval === 250 ? 250 : state.interval - 250}));
        this.startSlideshow();
    }
    render() {
        return (
            <>
                <button  onClick={() => this.startSlideshow()}>Start</button>
                <button  onClick={() => this.pause()}>Pause</button>
                <button  onClick={() => this.slowDown()}>Slow down</button>
                <button  onClick={() => this.speedUp()}>Speed up</button>
                <img src={"images/" data[this.state.ImgId].filename} className="w-100"/>
                <h6 className="text-center">{data[this.state.ImgId].filename}</h6>
            </>
        );
    }
}

CodePudding user response:

Use like :

slowDown() {
    this.setState((state) => ({...state, interval: state.interval   250}), ()=>{
        this.startSlideshow();
    );
    
}
speedUp() {
    this.setState((state) => ({...state, interval: state.interval === 250 ? 250 : state.interval - 250}), ()=>{
      this.startSlideshow();
    );
    
}

setState have a callback, trigger after setting complete
  • Related