Jaskaran Zap
Jaskaran Zap

Reputation: 277

call function after some time but only one time

I want to call function in javascript only a one time but after some time.

setTimeout(function(){ $('.alert').fadeOut(2000) }, 5000);

right now i am using this, But this function call multiple time. I need to call only a single time after some time

Upvotes: 1

Views: 1723

Answers (1)

David Snabel
David Snabel

Reputation: 10079

If you have for example a function like this:

function a () {
    // do stuff
    setTimeout(function() {
        // the timeout function
    }, 5000);
}

When this function a() is called multiple times. The timeout function will occur multiple times aswell.

To prevent this from happening you could either set the timeout function somewhere else. But you can also use a lock mechanism.

var lock = false;

function a () {
    // do stuff
    if (!lock) {
        lock = true;
        setTimeout(function() {
            // the timeout function
        }, 5000);
    }
}

a(); // first call

a(); // second call

lock = false;

a(); // third call

Now the first time you call function a it executes the timeout function. The second time it doesn't. To demostrate that you can control the lock you will see that the third one does execute the timeout function.

Upvotes: 2

Related Questions