1

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>

3 Answers 3

0

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. Only when it is, then you should invoke rotate() again.

const phrases = ['Word1', 'Word2', 'Word3', 'Word4', 'Word5', 'Word6'];
let index = 0;

function rotate() {
  document.getElementById('text-rotator').innerText = phrases[index];
  if (++index < phrases.length)
    setTimeout(rotate, 700);
}

rotate();
<span id="text-rotator"></span>

Sign up to request clarification or add additional context in comments.

Comments

0

The loop never ends because you keep calling setTimeout regardless of the counter

Here is an alternative way using setInterval which only needs to be run once

const phrases = ['Word1', 'Word2', 'Word3', 'Word4', 'Word5', 'Word6'];
let index = 0, tId, rotator= document.getElementById('text-rotator');

function rotate() {
  rotator.innerText = phrases[index++];
  if (index >= phrases.length) clearInterval(tId);
}
tId = setInterval(rotate,700);
<span id="text-rotator"></span>

2 Comments

There's no need to use setInterval in the first place. Just conditionally handle the timeout.
I personally prefer the interval since it is only executed once.
0

This is a recursive call of the rotate function. setTimeout() can only delay but not terminate. A termination condition needs to be added. In addition to setTimeout() and setInterval(), we can also use async/await and promise to achieve.

const phrases = ["Word1", "Word2", "Word3", "Word4", "Word5", "Word6"];

async function rotate() {
  for(let item of phrases) {
    document.getElementById("text-rotator").innerText = item;
    await new Promise(resolve => setTimeout(resolve, 700));
  }
}

rotate();
 <span id="text-rotator"></span>

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.