r_31415
r_31415

Reputation: 8982

Weird setTimeout issue

I have this problem. I defined a function to remove a link (just for the sake of example), so I want that after a mouseleave event on the link, it will disappear after 5 seconds (or whatever). Furthermore, if I mouseenter over the same link (which ostensibly has setTimeout running), that setTimeout is cancelled. For example, the following code works but as I'm not defining my setTimeout, I can't cancel it.

function func() { $('a').remove(); }
    //var interval = setTimeout( func , 5000);

    $('body').on('mouseleave', 'a', function() {
        setTimeout( func , 5000);
    });

    $('body').on('mouseenter', 'a', function(){
    //    clearTimeout(interval)
    });

Instead, uncommenting the second line, makes the link disappear immediately, even although I'm using the function func without parenthesis, so I would have thought that wouldn't be a problem (fiddle):

function func() { $('a').remove(); }
    var interval = setTimeout( func , 5000);

    $('body').on('mouseleave', 'a', function() {
        interval
    });

    $('body').on('mouseenter', 'a', function(){
    //    clearTimeout(interval)
    });

What can I do to achieve the intended functionality?.

Thanks!

Upvotes: 0

Views: 213

Answers (1)

Matt Ball
Matt Ball

Reputation: 359826

You need to combinerate (yes, that's a technical term) your two attempts. Declare interval outside of func and the mouse handlers, so that it can be referenced by both handlers.

function func() {
    $('a').remove();
}

var interval;

$('body').on('mouseleave', 'a', function() {
    interval = setTimeout(func, 5000);
});

$('body').on('mouseenter', 'a', function() {
    clearTimeout(interval);
});​

http://jsfiddle.net/mattball/2XN9a/

Upvotes: 2

Related Questions