I am trying to build an analog clock with the second hand rotating every second, min hand rotating 6deg every minute and hour hand rotating 6deg every 12 minutes.
Here's the codesandbox: https://codesandbox.io/s/react-example-d7mes?file=/Clock.js
Whenever the min hand's angle is either of these [72, 144, 216, 288, 360] (12 minute degrees), I rotate the hour hand by 6 degrees once.
This is what I'm doing:
let twelveMinDegrees = [72, 144, 216, 288, 360];
setInterval(() => {
this.setState(prev => ({
sec: prev.sec == 360 ? 6 : prev.sec + 6, //degrees
min: prev.sec == 354 ? (prev.min == 360 ? 6 : prev.min + 6) : prev.min, //degrees
hrs: (function(){ //degrees
const indx = twelveMinDegrees.findIndex(el => el == prev.min)
if(!minChanged && indx >=0){ //only change once for every 12min
minChanged = true;
let incHrs = prev.hrs + (6*indx);
console.log(incHrs);
return incHrs;
}else{
if(!twelveMinDegrees.includes(prev.min)){
minChanged = false;
}
return prev.hrs;
}
})()
}))
}, 1000)
But the hour hand does not change and is set back to the previous value in the else part the second time and the value returned incHrs is neglected because before the state is updated, the else is called the next second which returns prev.hrs which is still the old value(not the value returned in the if(!minChanged && indx >=0))
How do I fix this?