Business
Jobs
  • About Us
  • Solutions
    • Job Postings
      Post your job and receive qualified candidates in 48h.
    • Candidate Assessments
      500+ technical and psychological tests, plus anti-fraud.
    • Headhunting
      Tailor-made executive search from start to finish.
    • Payroll + EOR
      Payroll dispersal and EOR across 15+ LATAM countries.
  • Pricing
  • Jobs

0

185
Views
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 answers
Answer question

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 Report
Answer question
Find remote jobs

Discover the new way to find a job!

Top jobs
Top job categories
Business
Post vacancy Pricing Sales
Legal
Terms and conditions Privacy policy
© 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Show me some job opportunities
There's an error!