user2257938
user2257938

Reputation:

How to execute the function once?

$("#div1, #div2").fadeIn('500',function(){
    {
        console.log('Test');
    }
});

Fiddle here: http://jsfiddle.net/y97h9/

The above code will print 'Test' two times in the console. How can I make it print only one time. Is it possible?

Upvotes: 8

Views: 507

Answers (3)

Eli
Eli

Reputation: 14827

Sure, you can use jQuery promise to solve multiple callbacks problem:

$("#div1, #div2").fadeIn('500').promise().done(function()
{
    console.log('Test');
});

The .promise() method returns a dynamically generated Promise that is resolved once all actions of a certain type bound to the collection, queued or not, have ended

Working Demo

Upvotes: 27

Ryan Stutes
Ryan Stutes

Reputation: 1

Use a boolean flag to prevent console.log('Test'); from being called twice.

var isCalled = false;
$("#div1, #div2").fadeIn('500',function(){
    if(!isCalled) {
        isCalled = true;
        console.log('Test');
    }
});

Upvotes: -1

jmar777
jmar777

Reputation: 39659

The callback will run once for every matched element. You can always set a flag to see if it's been run already though:

var hasRun = false;
$("#div1, #div2").fadeIn('500', function() {
    if (hasRun) return;
    console.log('Test');
    hasRun = true;
});

Upvotes: 3

Related Questions