0

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);
        });
    });
}
0

2 Answers 2

3

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.

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

9 Comments

I need to be sure if the function in the timeout is called! How can I do that?
@XIII: What does this have to do with how quickly the timeouts are called? Maybe you should explain what you are actually trying to do. Asking for a solution to a problem is often better than asking for a solution to a solution.
I need to call a queue of functions one after another and I can't use callbacks.
@XIII why can't you use callbacks? That's the only way to trigger an action for "later" in Javascript. Your existing code is using callbacks anyway!
It's a kind of animation. But in my code, it all runs in the same time!
|
0

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);

5 Comments

You don't pass any time to the inner timeout... on purpose?
I don't understand this concept!
@XIII don't worry, it's not just you. this code doesn't work.
Sorry for the mistake. i edited the code. Set timeout to main function, so it should fix your issue.
@zonf no, it still won't work. Per Felix's comment, you never set a timeout on the inner call to setTimeout.

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.