Veo
Veo

Reputation: 291

Animated/timed text with JavaScript return

I have the following code:

function list() {
    return "blob1<br>blob2<br>blob3";
}

When this code is run, it directly displays the whole text in return on the call of the function.

Is there a way to make it display blob1, then wait for 0.5 seconds, then display blob2, then after 0.5 more seconds display blob3?

Upvotes: 0

Views: 253

Answers (3)

Kolby
Kolby

Reputation: 2865

function list(num) {
    return "blob" + num;
}

var num = 1;

setInterval(function(){
    list(num);
    num ++;
}, 500);

http://jsfiddle.net/yfhxgenf/

So this code is calling the list function every half a second and sending in a number. The number gets incremented by 1 every time the interval is ran.

The list function will return blob1, blob2, blob3, blob4, blob5, and so on, every half a second.

Check out the jsfiddle and open the console to see the result.

Also, I'm assuming you're doing something further with this string. Right now it's not being displayed anywhere.

And, if you only want it to go to 3 you can add a check to destroy the interval when the num gets to 3.

http://jsfiddle.net/yfhxgenf/1/

Upvotes: 0

Samuel Liew
Samuel Liew

Reputation: 79032

This is how I might do it:

var stack = ["blob1", "blob2", "blob3"];

function nextItem() {
    document.body.innerHTML += stack.shift() + "<br>";
}

nextItem();
setTimeout(nextItem, 500);
setTimeout(nextItem, 1000);

Upvotes: 1

Oriol
Oriol

Reputation: 288220

You can use setTimeout to delay the execution of a function:

var text = ["blob1", "blob2", "blob3"],
    target = document.getElementById('target');
(function display() {
    if(!text.length) return;
    target.textContent = text.shift();
    setTimeout(display, 500);
})();
<div id="target"></div>

Upvotes: 0

Related Questions