Firefox setInterval() strange behaviour
by AlmostDeadDude
HTML
<div id="circle" style='transform: rotate(0deg)'>
<span>
Click to rotate
</span>
<span id="angle">0 deg</span>
</div>
CSS
body{
display: flex;
align-items: center;
justify-content: center;
margin: 0;
height: 100vh;
font-family: sans-serif;
}
#circle{
border-radius: 50%;
background-color: skyblue;
width: 100px;
height: 100px;
display: flex;
flex-direction: column;
align-items: center;
justify-content: center;
cursor: pointer;
}
JavaScript
const circle = document.getElementById('circle')
const angle = document.getElementById('angle')
const degToMove = 90 //rotate 90 degrees
const animStepLength = 10 // 10ms is one animation step
const animLength = 300 //whole animation length -> 30 animation steps -> 3deg rotation per step
const rotateCircle = () => {
rotInterval = setInterval(()=>{
//what rotation value currently is
let currentVal = circle.style.transform.match(/[-+]?\d+/);
//add 3 deg rotation per step to it
circle.style.transform = `rotate(${+currentVal[0] + (degToMove*animStepLength) / animLength}deg)`
//text output
angle.innerHTML = `${+currentVal[0] + (degToMove*animStepLength) / animLength} deg`
}, animStepLength)
setTimeout(() => {
//after all steps are done clear the interval
clearInterval(rotInterval)
}, animLength);
}
circle.addEventListener('click', rotateCircle)