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

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.
timing(){
setInterval(() => {
this.setState({
stateName : new-state-value
})
}, time)
}
Example 1: This example illustrates how to change the state continuously after a certain amount of time.
index.js:Â
Javascript
import React from 'react'import ReactDOM from 'react-dom'import App from './App'Â Â ReactDOM.render(<App />, document.querySelector('#root')) |
App.js:
Javascript
import React, { Component } from 'react'Â Â class App extends Component { Â Â constructor(props){ Â Â Â Â super(props) Â Â Â Â this.state = {Number : 0} Â Â Â Â this.makeTimer() Â Â } Â Â Â Â makeTimer(){ Â Â Â Â setInterval(() => { Â Â Â Â Â Â let rand = Math.floor(Math.random() * 10) + 1 Â Â Â Â Â Â Â Â this.setState({number: rand}) Â Â Â Â }, 1000) Â Â } Â Â render(){ Â Â Â Â return ( Â Â Â Â Â Â <div> Â Â Â Â Â Â Â Â <h1> Â Â Â Â Â Â Â Â Â Â Random Number :Â Â Â Â Â Â Â Â Â Â Â {this.state.number} Â Â Â Â Â Â Â Â </h1> Â Â Â Â Â Â </div> Â Â Â Â ) Â Â } } Â Â export default App |
Output:Â
Whether you’re preparing for your first job interview or aiming to upskill in this ever-evolving tech landscape, zambiatek Courses are your key to success. We provide top-quality content at affordable prices, all geared towards accelerating your growth in a time-bound manner. Join the millions we’ve already empowered, and we’re here to do the same for you. Don’t miss out – check it out now!




