Check the console inside this sandbox: https://codesandbox.io/s/twilight-thunder-c71ov?file=/src/App.js
function Subjects({ logoArray }) {
const item1 = useRef();
const item2 = useRef();
const item3 = useRef();
const item4 = useRef();
const [images, setImages] = useState({ arr: logoArray, hasmoved: 0 });
setInterval(() => {
let randomChoice = Math.floor(Math.random() * 4);
let randomSwitch =
Math.floor(Math.random() * (images.arr.length - 1 - 4 + 1)) + 4;
// Handle Randomchoice
if (randomChoice === images.hasmoved) {
if (images.hasmoved === 3) randomChoice--;
else randomChoice++;
}
let updatedArray = images.arr;
let changeThis = updatedArray[randomChoice];
let switchThis = updatedArray[randomSwitch];
updatedArray[randomChoice] = switchThis;
updatedArray[randomSwitch] = changeThis;
setImages({ arr: updatedArray, hasmoved: randomChoice });
console.log("Happened");
}, 5000);
const handleTransition = (ev, n) => {};
return (
<>
<li
ref={item1}
onTransitionEnd={(ev) => handleTransition(ev, item1)}
className="bar-item"
></li>
<li
ref={item2}
onTransitionEnd={(ev) => handleTransition(ev, item2)}
className="bar-item"
></li>
<li
ref={item3}
onTransitionEnd={(ev) => handleTransition(ev, item3)}
className="bar-item"
></li>
<li
ref={item4}
onTransitionEnd={(ev) => handleTransition(ev, item4)}
className="bar-item"
></li>
</>
);
}
Every time "happened" is logged to the console my setInterval() function has completed, but it's only supposed to run once every five second.
Can anyone explain to me, why this happens and possibly come up with a solution?
Subjectrerenders you are creating an additional interval, i.e. you will have more and more intervals running at the same time. Have a look at reactjs.org/docs/hooks-reference.html#useeffect . - Felix Kling