Patrick
Patrick

Reputation: 3367

multiple setTimeouts cancel each other out?

I have an issue when I call multiple setTimeouts, It seems they cancel each other out when fired rapidly one after the other.

Given this fiddle : http://jsfiddle.net/72M6L/ .

which shows this very simple object:

fadepopup = function (msg) 
{
    $elm = $('<div class="fadepopup"></div>');
    $elm.html('msg');
    $('body').append($elm);

    setTimeout(function () 
    {
        $elm.fadeOut(500, function () 
        {
            $(this).remove()
        });
    }, 1500);
}

If you push the button once(in the fiddle), everything is great.
If you push the button multiple time quickly, the div does not get removed.

Why does this happen, and how can I fix it?

Upvotes: 1

Views: 92

Answers (1)

bozdoz
bozdoz

Reputation: 12860

You are using the global variable $elm. When you click the button before the timeout has executed the variable has been overwritten, and the method ($elm.fadeOut) is no longer bound to that element (because the variable refers to the newest element that was created instead).

My suggestion is to use var within the function to make it local:

var $elm = $('<div class="fadepopup"></div>');

See update fiddle

Upvotes: 5

Related Questions