Tejas Ramdas
Tejas Ramdas

Reputation: 129

Appending to empty element does not work

I want to display the characters of a string, stored in an array, one by one. When I call threadsleep(a) using the following code: http://jsfiddle.net/thefiddler99/re3qpuoo/, it appears all at once. The problem lies somewhere here I presume

for (var i = 0; i < str.length; i++) {
        $('#hello').append(str[i])
        alert("foo")
        sleep(500)  
};

The alert shows that everything is working properly except that the interval between each is not present.

I cannot figure out why.

Note: Sleep is a function I have defined that works for the set amount of time

Upvotes: 1

Views: 63

Answers (2)

ashokhein
ashokhein

Reputation: 1058

Just try with setTimeOut recursion call.

Demo

<script>  
  var text="This string will be display one by one.";
    var delay=500;
    var elem = $("#oneByOne");
    var addTextByDelay = function(text,elem,delay){
        if(!delay){
            delay = 500;
        }
        if(text.length >0){
            //append first character 
            elem.append(text[0]);
            setTimeout(
                function(){
                    //Slice text by 1 character and call function again                
                    addTextByDelay(text.slice(1),elem,delay);            
                 },delay                 
                );
        }
    }

    addTextByDelay(text,elem,delay);
</script>  

Upvotes: 0

Quentin
Quentin

Reputation: 943214

JavaScript is single threaded. It is too busy running round and round your while loop to perform a repaint of the page.

Don't try to write a sleep function. The language isn't suited to it and it just chomps CPU. Rewrite your code to use setInterval or setTimeout instead.

var i = 0;

next();

function next() {
    $('#hello').append(str[i]);
    i++;
    if (i < str.length) {
        setTimeout(next, 500);
    }
}

Upvotes: 4

Related Questions