ClearTimeout on Mouseover Event does not clear setTimeout from Mouseout Event

I have code that adds mouseover events and mouseout events to all the 'a' tags on the page. I would like the mouse to start a 5 second timer, after which it calls a function. However, if a new mouseover event occurs, it should cancel any existing timers. The code that I use follows. SetTimeout () works fine, but it seems like clearTimeout () is not referencing the correct timeout, although 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();
});

, . , . mouseover, . mouseout - , mouseout.

+3
2

timeoutId globall, $('a').each(). 1.4, , delay. timeoutId $(this).data('timeoutId', setTimeout (youFunction) `.

+2

, , , .each() . .

(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);
    });
}());

, - , .

+4

Source: https://habr.com/ru/post/1758835/


All Articles