0

I want to take the innerHTML of a div and then split the string into words and change the same innerHTML to display each word one by one with a delay in between. My code below at the moment does not work:

document.addEventListener("click", function() {
    var text = document.getElementById("article-text");
    var textSplit = text.innerHTML.split(" ");
    function timeoutFunction()
    {
        for (var i = 0; i < textSplit.length; i++) setTimeout(function () {
            text.innerHTML = textSplit[i];

        }, 500);
    }
    timeoutFunction();
});

3 Answers3

1

What about this, using recursion? call the same function and pass the index, when the index reaches the end of the loop, the recursion ends

document.addEventListener("click", function() {
    var text = document.getElementById("article-text");
    var textSplit = text.innerHTML.split(" ");

    function timeoutFunction(index){
        text.innerHTML = textSplit[index];
        // Recursion
        if(index < textSplit.length - 1){
            setTimeout(function(){
                timeoutFunction(index + 1);
            }, 500);
        }
    }


    timeoutFunction(0);
});
Luis Cabrera Benito
  • 1,558
  • 13
  • 21
1

At the first time, you think that calling multiple setTimeouts the effect will be as you expect, but actually that's not the case.

An alternative is to multiply the millis vs the index i to accomplish the effect. One more thing, you should use the statement let to keep the scope of the index i.

document.addEventListener("click", function() {
  var text = document.getElementById("article-text");
  var textSplit = text.innerHTML.split(" ");

  text.innerHTML = '';

  function timeoutFunction() {
    for (let i = 0; i < textSplit.length; i++) {
      setTimeout(function() {
        text.innerHTML += ' ' + textSplit[i];
      }, 500 * i + 1);
    }
  }
  
  timeoutFunction();
});
Click on this screen!
<div id='article-text'>Ele from Stack</div>
Ele
  • 33,468
  • 7
  • 37
  • 75
-1

Just use the array as a queue and work it until it's done. .shift() pulls the next item from the array.

document.addEventListener("click", function() {
    var text = document.getElementById("article-text");
    var textSplit = text.innerHTML.split(" ");
    var runUp = text.innerHTML = '';
    function timeoutFunction()
    {
        runUp += ' ' + textSplit.shift();
        text.innerHTML = runUp;
        if (textSplit.length) setTimeout(timeoutFunction, 500);
    }
    timeoutFunction();
});
Tracker1
  • 19,103
  • 12
  • 80
  • 106