Empresas
Empleos
  • Sobre nosotros
  • Soluciones
    • Publicación de vacantes
      Publica tu vacante y recibe candidatos calificados en 48h.
    • Evaluación de candidatos
      500+ pruebas técnicas y psicológicas, más anti-fraude.
    • Headhunting
      Búsqueda ejecutiva a la medida de principio a fin.
    • Nómina + EOR
      Dispersión de nómina y EOR en más de 15 países de LATAM.
  • Precios
  • Empleos

0

174
Vistas
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>
            </>
        );
    }
}
about 4 years ago · Juan Pablo Isaza
1 Respuestas
Responde la pregunta

0

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
about 4 years ago · Juan Pablo Isaza Denunciar
Responde la pregunta
Encuentra empleos remotos

¡Descubre la nueva forma de encontrar empleo!

Top de empleos
Top categorías de empleo
Empresas
Publicar vacante Precios Comercial
Legal
Términos y condiciones Política de privacidad
© 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Recomiéndame algunas ofertas
Necesito ayuda