0

Ok, the title might make it sound easy (and maybe it is), but I can't figure out how to show values from an array, not just do a each with them, but put them on the site slowly, with a nice effect...

Like this Twitter widget, but from an array (maybe wait 2sec, and when throw another value from the array)?

My array contains another array, with 4 values, is it possible to show the first 2 values, wait about 2 sec, and then show the last 2 values? Now when the last two values is out (from the prev array), wait 2 more seconds, and show the next array (again with four values, first show 2, wait 2 sec, and show the next 2, and so on...)

0

2 Answers 2

4

You can do this easily using setInterval or a chained series of setTimeout. I tend to prefer the latter, which looks something like this:

function showValues(a, delay) {
    var index = 0;

    if (a.length !== 0) {
        // If you want a delay before the first one:
        setTimeout(showValue, delay);

        // Alternately, if you want to show the first right away
        // showValue();
    }

    // Function to show one value
    function showValue() {
        // Get the value
        var value = a[index++];

        /* ...show the value however you see fit... */

        // Schedule next display, if any
        if (index < a.length) {
            // Schedule next run
            setTimeout(showValue, delay);
        }
    }
}

Usage:

showValues(["value1", "value2", /* etc. */, 2000); 2000 = two seconds

Live example | source

Sign up to request clarification or add additional context in comments.

3 Comments

@Moiblpadde: It's just an extension of the same technique.
Awesome! Figured it out :D I feel kinda stupid right now D: (Was pretty simple through, once I took a look at the code :3) Final code
@Moiblpadde: Good deal! Glad that helped.
4

Animation functions like fadeIn() make use of the jQuery FX queue so you can use .delay() in the call chain to delay the calling of these functions. In the following example one element is shown every second.

var data = ['foo', 'bar', 'foobar', 'moo', 'meow', 'xxx'];
var list = $('ul');
$.each(data, function(i, value) {
    $('<li/>', { text: value }).hide().appendTo(list).delay(i * 1000).fadeIn();
});

Demo: http://jsfiddle.net/ThiefMaster/frW8s/

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.