2

I am totally stumped here.

I have a bunch of messages, each within a div "msg_feed_frame_$i" which increases, so message 1 is in div "msg_feed_frame_1", msg 2 is in "msg_feed_frame_2", etc etc. I want to fade these messages in one by one using jquery, but for some reason no matter what I do with settimeout and setinterval, the code immediately fades them all in simultaneously.

This is what i've got so far:

function feed(i)
{
    var div = "#msg_feed_frame_";
    var fader = div.concat(i);
    $(fader).fadeIn(2000);

}

function timefade()
{
var num = 1;
for (num=1; num<=10; num++)
{
var t=setTimeout(feed(num),1000);
}
}

$(document).ready(function(){
        timefade();
    });
Trufa
  • 39,971
  • 43
  • 126
  • 190
  • Hi, welcome to StackOverflow, please format you code correctly (did it for you this time). To learn how to do it, please click the orange question mark in the ask question text area. – Trufa May 03 '11 at 01:51

2 Answers2

1

Your problem is that the for loop executes quickly and sets a timeout 1000ms from now for each function call. Here's one way you could remedy this:

function feed(i) {
    var div = "#msg_feed_frame_";
    var fader = div.concat(i);
    $(fader).fadeIn(2000);

}

function timefade() {
    var num = 1;
    var fadeIt = function(i) {
        return function() { feed(i); };
    };
    for (num = 1; num <= 4; num++) {
        var t = setTimeout(fadeIt(num), num * 1000);
    }
}

$(document).ready(function() {
    timefade();
});

Additionally, your original code was passing setTimeout the results of the feed(i) function call (undefined), and it expects an object of type function. I added a helper function that returns a reference to a function that will call feed with the correct argument.

Capturing the value of num inside a function is called a closure, and it can be confusing at first. Check this post out for some good explanations of closures inside loops and while they're necessary.

Here's your example, working: http://jsfiddle.net/andrewwhitaker/tpGXt/

Community
  • 1
  • 1
Andrew Whitaker
  • 124,656
  • 32
  • 289
  • 307
0

Try using jQuery's .delay() function...

    function feed(i){
    var div = "#msg_feed_frame_";
    var fader = div.concat(i);
    $(fader).fadeIn(2000).delay(1000);
}
function timefade(){
 var num = 1;
 for (num=1; num<=10; num++){
   feed(num);
 }
}
$(document).ready(function(){
        timefade();
});
Thomas Shields
  • 8,874
  • 5
  • 42
  • 77