How to tell .hover() to wait?

This will make the second function wait 2 seconds (2000 milliseconds) before executing:

$('.icon').hover(function() {
    clearTimeout($(this).data('timeout'));
    $('li.icon > ul').slideDown('fast');
}, function() {
    var t = setTimeout(function() {
        $('li.icon > ul').slideUp('fast');
    }, 2000);
    $(this).data('timeout', t);
});

It also clears the timeout when the user hovers back in to avoid crazy behavior.

This is not a very elegant way of doing this, however. You should probably check out the hoverIntent plugin, which is designed to solve this particular problem.

Leave a Comment