Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

React setState in setInterval not updated immediately

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>
            </>
        );
    }
}

>Solution :

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

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
Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading