Answer the question
In order to leave comments, you need to log in
How to update state by timer?
Hello. Please tell me how can I update the state once per second? I have created a time counter and I need to output it to a react component, I try it like this:
const date = {
hours: 0,
minutes: 0,
seconds: 0,
isActive: false,
start: function() {
this.isActive = true;
return this
},
stop: function() {
this.isActive = false;
return this
}
}
function timer() {
if(this.isActive) {
if(this.seconds < 60) date.seconds += 1;
else {
this.seconds = 0;
if(this.minutes < 60) date.minutes += 1;
else {
this.minutes = 0;
this.hours += 1;
}
}
}
return this
}
const myTimer = timer.bind(date);
const [timerState, setTimerState] = useState({});
let interval;
useEffect(() => {
if(interval) clearInterval(interval);
interval = setInterval(() => {
if(clients.length > 1) {
setTimerState(myTimer().start());
} else {
setTimerState(myTimer().stop());
}
console.log(timerState);
}, 1000);
}, [clients, timerState]);
Answer the question
In order to leave comments, you need to log in
If you need exact time, then this is not the best idea. setInterval and setTimeout have lags that will show up over time.
The simplest timer is "the current time is the start time of the timer". Thus, it is necessary to store not the current position of the counter, but the time of the beginning of the countdown. But to draw it, yes, by interval.
those.:
const startTime = newDate().now()
setinterval(()=>{
formatTimeToYourNeeds(new Date().now() - startTime)
}, 1000)
Didn't find what you were looking for?
Ask your questionAsk a Question
731 491 924 answers to any question