'acceleration of rotation in react with setInterval
When i push the button it change the line on the page in accordance with position of arrow, but also i have a strange acceleration of the arrow. where is a problem?
element code:
const Synchroniser = () => {
const[result, setResult] = useState(0)
const[word, setWord] = useState("")
const point:any = useRef(null);
const k = useRef(0);
function calculateResult(){
var myvar = k.current
if (myvar<30 || myvar>330){
setWord("YOU ARE THE BEST ELECTRICIAN")
} else{
setWord("try again")
}
}
useEffect(() => {
if (point.current !== null) {
setInterval(() => {
if (k.current < 360) {
k.current = k.current + 3;
}
if (k.current >=360){
k.current = 0
}
point.current.style.transform = `rotate(${k.current}deg)`;
}, 10);
} else {
console.log("0");
}
});
return(
<div>
<div className={classes.synchroniser}>
<img src={arpng} ref={point} alt="arrow" className={classes.ar} />
<img src={syncFrame} alt="syncframe" className={classes.syn} />
</div>
<div >
<Button variant='contained' onClick={calculateResult}>SYNCHRONISE</Button>
<h1> {word} </h1>
</div>
</div>
);
};
export default Synchroniser
You can see that reaction link: http://sugwox.ru/
Solution 1:[1]
I think it relates with a manytime starts of setInterval when i render a page with different words, so i clear the interval every time:
useEffect(() => {
if (point.current !== null) {
const inter = setInterval(() => {
if (k.current < 360) {
k.current = k.current + 5;
}
if (k.current >=360){
k.current = 0
}
point.current.style.transform = `rotate(${k.current}deg)`;
}, 10);
return () => clearInterval(inter)
} else {
console.log("0");
}
Sources
This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.
Source: Stack Overflow
Solution | Source |
---|---|
Solution 1 | Vladimir Kosilov |