moonshineOutlaw
moonshineOutlaw

Reputation: 723

problems with setTimeout() repeating action

I have a variable that contains a string that I've split() into an array and use shift() method to print out one letter at a time to a div. I've used setTimeout to repeat the process and print out the entire string. The problem I'm having is that the function is printing out the first letter repeatedly without moving to the next letter in the string. I've used the only ways I know of using setTimeout with parameters nothing seems to be working.

Where is the problem here in the code ?

<div id='ltrType'></div>
<script>
function buildWord(str) {
    var arr = str.split('');

    if(arr.length > 0) {
        document.getElementById('ltrType').innerHTML += arr.shift();
    } else {
        clearTimeout(timer);
    }

    //I've tried setTimeoout like this
    timer = setTimeout(buildWord,100,str);

    //and like this
    timer = setTimeout(function(){ buildWord(str); })
}

buildWord('this is another string blah blah blah');

Upvotes: 1

Views: 124

Answers (3)

Arsen Mkrtchyan
Arsen Mkrtchyan

Reputation: 50712

Because you are building initial array each time on method call, move it outside

function buildWord(str)
{
   var arr = str.split(' ');

   var helper = function buildWordHelper()
   {       
        if(arr.length > 0) {
            document.getElementById('ltrType').innerHTML += arr.shift();
       } else {
            clearTimeout(timer);
       }

       setTimeout(helper, 100);
   }
   setTimeout(helper, 100);
}

buildWord("bla bla1 bla123");

Upvotes: 1

user2509211
user2509211

Reputation:

beacuse arr is getting initalized everytime to the same value, you call buildword,again and again ,as you are passing str.Try putting it outside of function.

var arr=null;
var firsttime=0;
function buildWord(str)
{
if(firsttime==0)
{ arr=str.split('');firsttime=1;}
.....
}

Upvotes: 0

Hans Roerdinkholder
Hans Roerdinkholder

Reputation: 3000

You keep passing in str, while it is arr that you shift. So basically you keep passing the same string every time, and the first character is the same every time. Instead, do it like this:

function buildWord(arr) {
    if (typeof arr === "string") {
        arr = arr.split('');
    } 
    if (arr.length) {
        document.getElementById('ltrType').innerHTML += arr.shift();
        setTimeout(function () {
            buildWord(arr);
        }, 100);
    }
}

buildWord('this is another string blah blah blah');

Upvotes: 2

Related Questions