Toan Hong
Toan Hong

Reputation: 31

Run a function after each function

For some reason, I can't get a function to run after the each function is complete. This is what I tried and the each function works perfectly but it does not run the other function when it is complete.

var delay = 0;
$('h1 span').each(function() {
    var $span = $(this);
    setTimeout(function() { $span.addClass('visible'); }, delay+=1000, function(){
        $('header').addClass('visible');
    });
});

Upvotes: 0

Views: 80

Answers (4)

A. Wolff
A. Wolff

Reputation: 74420

If i understand your expected behaviour, you can use following logic inside delayed function:

var delay = 0;
$('h1 span').each(function () {
    var $span = $(this);
    setTimeout(function () {
        $span.addClass('visible');
        // if $span is last of 'h1 span' matched set
        if ($span.is($('h1 span').last())) {
            $('header').addClass('visible');
        }
    }, delay += 1000);
});

-DEMO-

Upvotes: 1

gon250
gon250

Reputation: 3545

I think what you want to do is this http://jsfiddle.net/gon250/8mdodywe/

setTimeout() function doesn't support two callbacks.

$.when($('span').each(function() {
    $(this).addClass('visible');
})).then(function(){
    $('header').addClass('visible');
});

Upvotes: 1

Peter Fischaleck
Peter Fischaleck

Reputation: 342

I'm assuming, you want two timeouts? From your Code it seems you would like to execute the first timeout after "delay 0". In that case simply execute the first "callback" and set a timout for the second. If you do indeed want two timeouts (each after 1000ms):

$('h1 span').each(function() {
    var $span = $(this);
    setTimeout(
        function() { 
            $span.addClass('visible');
            setTimeout( 
                function() {
                   $('header').addClass('visible');
                },
                1000
             );        
        }, 
        1000        
    );
});

Upvotes: 0

Jordi Nebot
Jordi Nebot

Reputation: 3401

I guess that's what you want:

var delay = 0;
$('h1 span').each(function() {
    var $span = $(this);
    setTimeout(function() { $span.addClass('visible'); }, delay+=1000);
});
setTimeout(function() { $('header').addClass('visible'); }, delay);

Check it out: http://jsfiddle.net/zsm4xegr/

Upvotes: 0

Related Questions