Home:ALL Converter>clearTimeout on Mouseover Event not clearing setTimeout from Mouseout Event

clearTimeout on Mouseover Event not clearing setTimeout from Mouseout Event

Ask Time:2010-08-10T09:10:44         Author:ggutenberg

Json Formatter

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.

Author:ggutenberg,eproduced under the CC 4.0 BY-SA copyright license with a link to the original source and this disclaimer.
Link to original article:https://stackoverflow.com/questions/3445331/cleartimeout-on-mouseover-event-not-clearing-settimeout-from-mouseout-event
Ken Redler :

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.\n\n(function game () {\n var timeoutID;\n $('a').mouseover(function() {\n $('#box').html('All is well.').removeClass('bang');\n clearTimeout(timeoutID);\n // do stuff\n });\n $('a').mouseout(function() {\n $('#box').html('You have 2 seconds to return!');\n timeoutID = setTimeout(function() {\n $('#box').addClass('bang').html('Too Late!');\n // do stuff\n }, 2000);\n });\n}());\n\n\nIt's very possible I'm missing something -- but the hover game seems to work fine.",
2010-08-10T02:35:08
yy