0

I have the following code with the purpose of making each .feedcontain div fade in after an increasing delay. The animation and formatting is perfect, its just that I can't have a this keyword in the first setTimeout() parameter.

function goFadeNow(){
    var loopdelay=250;
    $(".feedcontain").each(function() {
        setTimeout('$('+this+').addClass("appeared");',loopdelay);
        //$(this).addClass("appeared");
        loopdelay=loopdelay+250;
    });
}

If I uncomment line 5 and comment line 4, it works but it doesn't have the delay. PS: I do realize that I can't just use this like a normal variable.

Sabreok
  • 65
  • 1
  • 2
  • 6

2 Answers2

3

You can also bind() the function you are passing to this pointer:

function timeoutFunc() {
  $(this).addClass("appeared");
}

function goFadeNow(){
  var loopdelay=250;

  $(".feedcontain").each(function() {
    setTimeout(timeoutFunc.bind(this), loopdelay);
    loopdelay=loopdelay+250;
  });
}
Shalom Aleichem
  • 2,897
  • 2
  • 20
  • 33
  • What advantage do you think this offers over Matt's answer if any and why? – Benjamin Gruenbaum Jun 16 '13 at 05:12
  • 2
    Matt's solution saves the context of `goFadeNow` function, but the author of the question asked to pass the context of `each` function. The idea is the same, but we can operate with different meanings of `this` in the `timeoutFunc` just rebinding it do different contexts. – Shalom Aleichem Jun 16 '13 at 05:18
2
function goFadeNow(){
    var loopdelay=250;
    $(".feedcontain").each(function() {
        var $this = $(this);
        setTimeout(function () {
            $this.addClass("appeared");
        }, loopdelay);
        loopdelay=loopdelay+250;
    });
}
Matt Ball
  • 344,413
  • 96
  • 627
  • 693