Skip to content
Related Articles
Open in App
Not now

Related Articles

How to change state continuously after a certain amount of time in React?

Improve Article
Save Article
  • Last Updated : 01 Sep, 2020
Improve Article
Save Article

To change a state continuously after a certain amount of time is required in a few cases for the toggling. First, make a function that is responsible for changing the state of the component. Then call the function from the constructor method for the first time.  Use the set interval method inside the function to change the state after a fixed amount of time. setInterval method takes two parameter callback and time. The callback function is called again and again after that given amount of time.  Use the setState method to change the state of the component.

  setInterval(() => {
      stateName : new-state-value
  }, time)

Example 1: This example illustrates how to change the state continuously after a certain amount of time.



import React from 'react'
import ReactDOM from 'react-dom'
import App from './App'
ReactDOM.render(<App />, document.querySelector('#root'))



import React, { Component } from 'react'
class App extends Component {
    this.state = {Number : 0}
    setInterval(() => {
      let rand = Math.floor(Math.random() * 10) + 1
        this.setState({number: rand})
    }, 1000)
    return (
          Random Number : 
export default App


My Personal Notes arrow_drop_up
Related Articles

Start Your Coding Journey Now!