how to set setInterval in reactjs
10,448
Try this:
trigger() {
let newTime = Date.now() - this.props.date;
setInterval(() => {
this.setState({
clock: newTime;
})
}, 1000);
}
You can execute this function in a variety of ways, with the best option likely being within the component or container's componentDidMount(). This will then run every second, updating the value of this.clock each time.
Related videos on Youtube
Author by
vivek modi
Updated on June 04, 2022Comments
-
vivek modi almost 2 years
i am trying to call a function in reactjs using
setInterval
like this:import React,{Component} from 'react'; class Timer extends Component { trigger(){ this.clock = this.setState({clock:Date.now()-this.props.date}); } setInterval(this.trigger,1000); constructor(props){ super(props); this.state = { clock:0 }; this.trigger = this.trigger.bind(this); } render(){ this.state.clock=Math.round(this.state.clock/1000); return( <div> <p>You are here since</p> <span>{this.state.clock}</span> <p>Seconds.</p> <button onClick={this.trigger}>Click me</button> </div> ); } } export default Timer;
Which returns this error instead:
Syntax error: F:/reactjs1/project-6/timer/src/Timer.js: Unexpected token (8:22) Syntax error: F:/reactjs1/project-6/timer/src/Timer.js: Unexpected token (8:22) 6 | this.clock = this.setState({clock:Date.now()-this.props.date}); 7 | } > 8 | setInterval(trigger,1000); ^
-
Metalik almost 6 yearstry
setInterval(this.trigger,1000);
and put in componentDidMount lifecycle. -
vivek modi almost 6 yearssame error is showing now its showing on this
-
Yossi almost 6 yearsPlease post the code of the entire component
-