Arash R
Arash R

Reputation: 412

Why javascript setTimeout does all at once?

I've got this code and I don't know why all the functions in the loop are called at once!

this.line = function($l) {
    var $this = this;
    $this.$len = 0;
    $('.active').hide(0,function(){             
        $this.$len = $l.length;
        var j = 1;
        $.each($l,function(i,item){
            var t = setTimeout(function(){
                $this._echoLine($l[i]);
                clearTimeout(t);
                if (j >= $this.$len) $('.active').show();
                j++;
            },500*j);
        });
    });
}

Upvotes: 0

Views: 203

Answers (2)

Alnitak
Alnitak

Reputation: 339816

It's because you only increment j inside the timeout function, but the delay (which depends on j) is still 1 at the time the timeout handler is registered.

Seeing as you have a loop index variable anyway (i), try this:

$l.each(function(i, item) {
    setTimeout(function() {
        $this._echoLine($l[i]);
    }, 500 * (i + 1));
});

// a separate timeout to fire after all the other ones
setTimeout(function() {
    $('.active').show();
}, ($l.length + 1) * 500);

There's no need for the clearTimeout line, so no need to declare or store t either.

Upvotes: 3

Zonf
Zonf

Reputation: 67

Hope it works.

this.line = function($l) {
    var $this = this;
    $this.$len = 0;
    $('.active').hide(0,function(){             
        $this.$len = $l.length;
        var j = 1;
        $.each($l,function(i,item){
            var t = setTimeout(function(){
                $this._echoLine($l[i]);
                clearTimeout(t);
                if (j >= $this.$len) $('.active').show();
                j++;
            });
        });
    });
}

setTimeout(function() { this.line(); }, 500);

Upvotes: 0

Related Questions