I have this code today
<span id="text-rotator"></span>
<script>
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();
</script>
This code works fine. But never end.
How can i stop the rotator after Word6?
I have tried one more setTimeout but its now working
New contributor
Andreas Thomsson is a new contributor to this site. Take care in asking for clarification, commenting, and answering.
Check out our Code of Conduct.
To stop the update at the end of the array, increment index
within the rotate()
function and check that it’s still within the bounds of the array. If it is not, do not call rotate()
again:
const phrases = ['Word1', 'Word2', 'Word3', 'Word4', 'Word5', 'Word6'];
let index = 0;
function rotate() {
document.getElementById('text-rotator').innerText = phrases[index];
index++
if (index < phrases.length)
setTimeout(rotate, 700);
}
rotate();
<span id="text-rotator"></span>