Dylan
Dylan

Reputation: 3

Display letters one after the other for a looped sequence

I want to display multiple strings one after the other and I want the letters in each string to appear one at a time until the string is complete and it loops to the next string. Should run on a continuous loop.

var example = ['IT Solutions', 'Professional Work Ethic'];
textSequence(0);
function textSequence(i) {
  if (example.length > i) {
    setTimeout(function() {
      document.getElementById("sequence").innerHTML = example[i];
      textSequence(++i);
    }, 4000);
  } else if (example.length == i) { // Loop
    textSequence(0);
  }
}
<div class="container" id="sequence"></div>

Upvotes: 0

Views: 358

Answers (2)

Phrogz
Phrogz

Reputation: 303224

I prefer @adpro's answer, but here's an alternative that keeps your original array:

showLettersOf(
  ['IT Solutions', 'Professional Work Ethic'],
  document.querySelector('#sequence')
); 

function showLettersOf(arrayOfStrings, el) {
  var stringIndex=0, letterIndex=0, str="";
  return setInterval(function(){
    str += arrayOfStrings[stringIndex].charAt(letterIndex++);
    el.innerHTML = str;
    if (letterIndex >= arrayOfStrings[stringIndex].length){
      letterIndex=0;
      str="";
      if (++stringIndex >= arrayOfStrings.length) stringIndex=0;
    }
  }, 100);
}

Upvotes: 1

adprocas
adprocas

Reputation: 1913

You can join the strings, and then loop over them almost the same as you are. But you'll want to hold on to the value and pass it in recursively to keep track of what you have already.

This may not be exactly what you want, but I think you'll be able to figure it out by using this.

var example = ['IT Solutions', 'Professional Work Ethic'];
var eString = example.join(' ');

textSequence(0, '');
function textSequence(i, value) {
  if (eString.length > i) {
    setTimeout(function() {
      value += eString[i];
      document.getElementById("sequence").innerHTML = value;
      textSequence(++i, value);
    }, 100);
  } else if (eString.length == i) { // Loop
    textSequence(0, '');
  }
}
<div class="container" id="sequence"></div>

Upvotes: 1

Related Questions