fguru
fguru

Reputation: 71

how to setTimeout delay .each loop

Is there a way to show these images with a time delay. Thanks in advance.

  $.each(people, function(i, data){

            if(this.dead == true){
                $('#item7').prepend(' <span style="position:relative; top: 7px;"><img src="images/alive.png"/> </span> ');
                }else if(this.dead == false){
                    $('#item7').prepend(' <span style="position:relative; top: 7px;"><img src="images/alive1.png"/> </span> ');
                }

    });

Upvotes: 0

Views: 120

Answers (3)

Flo Schild
Flo Schild

Reputation: 5294

Use setTimeout to delay it. What are those == true and == false operations ? If you want to ensure your dead property to be false or true, compare with ===, otherwise, a if () is enough.

$.each(people, function(i, data) {
    setTimeout(function() {
        $('#item7').prepend($('<span style="position:relative; top: 7px;">').html($('<img/>', { src : (this.dead ? "images/alive.png" : "images/alive1.png") })));
    }, i * 500);
});

Watch an exemple here: http://jsfiddle.net/cLhvf/

Upvotes: 0

thabubble
thabubble

Reputation: 640

It depends on what you mean.

var delay = 500; (function(elements, index) { elements[index];//do whatever you want to it. setTimeout(function(){arguments.calle(elements, index + 1);}, delay); })(people, 0)

$.each(people, function(i, data) { var self = this; setTimeout(function() { // do whatever you want here }, delay); });

I don't think delay works here. I could be wrong though

All code is untested.

Upvotes: 0

Alnitak
Alnitak

Reputation: 339786

Yes, there's a way. In fact there's lots of ways.

This is the one I'd probably use:

$.each(people, function(i, data) {
    var src = this.dead ? 'images/alive.png' : 'images/alive1.png';
    $('<span style="position:relative; top: 7px; display: none;">')
               .append($('<img>', { src: src }))
               .prependTo('#item7')
               .delay(i * 1000)
               .show('fast');
});

It ensures that the element is initially invisible (display: none) and then uses jQuery animation delays to queue up the .show() call.

Upvotes: 1

Related Questions