简体   繁体   中英

clearTimeout on Mouseover Event not clearing setTimeout from Mouseout Event

I have some code that adds mouseover events and mouseout events to all 'a' tags on a page. I'd like it so that the mouseout starts a 5 second timer after which time it calls a function. However, if a new mouseover event fires, it should cancel any existing timers. The code I'm using follows. The setTimeout() is working fine, but it seems like the clearTimeout() isn't referencing the right timeoutID, even though I declared it globally. Any suggestions?

var timeoutID;

function addMouseoverEvent() {
    $('a').each(function(index) {
        $(this).mouseover(function() {
            clearTimeout(timeoutID);
            // do stuff
        })
    }); 
}

function addMouseoutEvent() {
    $('a').each(function(index) {
        $(this).mouseout(function() {
            timeoutID = setTimeout(function() {
                // do stuff
            }, 5000);
        })
    });
}

$(window).load(function() {
    addMouseoverEvent();
    addMouseoutEvent();
});

I should clarify that there should really only ever be one active timer. That's why I wanted it to be global. If a mouseover event occurs no timers should remain. And if a mouseout event occurs only one timer should be active - the one triggered by the last mouseout event.

I know it's already been answered, but I found that simply removing the .each() call makes this appear to work as desired. Try the little hover game on this Fiddle .

(function game () {
    var timeoutID;
    $('a').mouseover(function() {
        $('#box').html('All is well.').removeClass('bang');
        clearTimeout(timeoutID);
        // do stuff
    });
    $('a').mouseout(function() {
        $('#box').html('You have 2 seconds to return!');
        timeoutID = setTimeout(function() {
            $('#box').addClass('bang').html('Too Late!');
            // do stuff
        }, 2000);
    });
}());

It's very possible I'm missing something -- but the hover game seems to work fine.

If your timeoutId is globall then its going to get overwritten on each iteration of $('a').each() . If youre using 1.4 you can use the delay method most likely. or you could store the timeoutId on the element with $(this).data('timeoutId', setTimeout(youFunction)`.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM