功能前延迟,悬停时取消功能

delay before function and cancel function on hover out

本文关键字:功能 取消 悬停 延迟      更新时间:2023-09-26

我正在尝试达到以下目的。我想在将鼠标悬停在菜单上超过 3 秒后折叠菜单。但是当我在 3 秒之前将鼠标悬停在菜单之外时,它一定不能崩溃。

$("#sidebar").hover(function() {
    if($(this).hasClass("collapsed-by-user")) {
        setTimeout(sidebarCollapse, 3000);
    }
}, function() {
    if($(this).hasClass("collapsed-by-user")) {
        sidebarNotCollapse();
        preventDefault();
    }
});

这就是我到目前为止得到的。3 秒后崩溃正在工作,但如果我在 3 秒前悬停,它仍然会崩溃。

知道怎么做吗?

您需要记住计时器句柄,并在悬停结束时(如果在 3 秒内)与clearTimeout一起使用:

var handle = 0;
var when = 0;
$("#sidebar").hover(function() {
    // Start the timer if we don't have it running already and we have the class
    if(!handle && $(this).hasClass("collapsed-by-user")) {
        handle = setTimeout(function() {
            handle = 0;
            sidebarCollapse();
        }, 3000);
        when = Date.now(); // Remember when it started
    }
}, function() {
    // If we have a handle and it's been less than three seconds,
    // stop the timeout from running by clearing it
    if (handle && Date.now() - when < 3000) {
        clearTimeout(handle);
    }
    // Reset our handle var regardless (for next time)
    handle = 0;
});

请注意,当计时器在 callilng sidebarCollapse 之前触发时,我们将清除handle

(我不确定你为什么要做那个类检查,所以我把它留了下来。

或者根据Jamiec下面的评论进行更新; 他是对的,我们真的不需要这样做when检查:

var handle = 0;
$("#sidebar").hover(function() {
    // Start the timer if we don't have it running already and we have the class
    if(!handle && $(this).hasClass("collapsed-by-user")) {
        handle = setTimeout(function() {
            handle = 0;
            sidebarCollapse();
        }, 3000);
    }
}, function() {
    // clearTimeout is a no-op if the timer's already fired
    clearTimeout(handle);
    handle = 0;
});