My code works fine, but it never ends. How can I stop the rotator after Word6
? I have tried one more setTimeout
but it’s not working.
const phrases = ['Word1', 'Word2', 'Word3', 'Word4', 'Word5', 'Word6'];
let index = 0;
function rotate() {
document.getElementById('text-rotator').innerText = phrases[index];
index = (index + 1) % phrases.length;
setTimeout(rotate, 700);
}
rotate();
<span id="text-rotator"></span>
2
Answers
To stop the update at the end of the array, increment
index
within therotate()
function and check that it’s still within the bounds of the array. Only when it is, then you should invokerotate()
again.The loop never ends because of the % will restart
Here is a "better" way