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

186
Vistas
How to call setState without any triggering events?

I want to update the value of a counter variable after some fixed time indefinitely. Here is my code:

class Counter extends React.Component {
  constructor(props) {
    super(props);
    
    this.state = {
      myCount: 1    
    };
  }
  
  // Update state after every 15 seconds.
  setTimeout(function(){
     this.setState({myCount: this.state.myCount + 1});
  }, 15000);
}


However, I get error about unexpected token with this component. How can I set state within the class properly without using any event listeners?

Thanks.

about 4 years ago · Juan Pablo Isaza
1 Respuestas
Responde la pregunta

0

Your call to setTimeout is at the top level of the class body where properties, the constructor, and methods are expected. You can't put arbitrary code there. (Though you could could have a property initializer; not a good idea in this case, though.)

Put it in componentDidMount; and be sure to saved the timer handle (on the instance, usually) and clear the timer in componentWillUnmount so it doesn't fire if the component is unmounted before the timer callback occurs:

class Counter extends React.Component {
    constructor(props) {
        super(props);

        this.state = {
            myCount: 1,
        };
    }

    componentDidMount() {
        // Update state after every 15 seconds.
        this.timerHandle = setTimeout(() => {                   // ****
            this.setState((previousState) => {                  // ****
                return { myCount: previousState.myCount + 1 };  // ****
            });                                                 // ****
        }, 15000);
    }

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

Side note: Notice the changes on the **** lines above

  • I replaced your traditional function with an arrow function so it closes over this.
  • I changed your callback to use the callback version of setState, which is generally best when setting state based on existing state.

...after some fixed time indefinitely.

A setTimeout callback will only occur once. You may want setInterval if you want the counter updated every 15 seconds. Or alternatively, start a new setTimeout when the callback runs, like this:

startCounterTimer() {
    // Update state after every 15 seconds.
    this.timerHandle = setTimeout(() => {
        this.setState((previousState) => {
            this.startCounterTimer(); // ***
            return { myCount: previousState.myCount + 1 };
        });
    }, 15000);
}

componentDidMount() {
    this.startCounterTimer();
}
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