过一段时间后观察mouseenter事件

Observe mouseenter event after sometime

本文关键字:mouseenter 事件 观察 一段时间      更新时间:2023-09-26

我有一个jquery代码,用于观察站点菜单栏上的mouseenter事件。

menubar.on('mouseenter', 'li.parent.level0', function() {
       ... function body
});

现在我想提供一个延迟,以便事件函数体在2000 ms之后执行,如下所示:

menubar.on('mouseenter', 'li.parent.level0', function() {
    delay(2000);
    ... function body
});

我尝试了以下方法:

menubar.on('mouseenter', 'li.parent.level0', function() {
        delay(2000);
        ... function body
    });
var delay = (function(){
  var timer = 0;
  return function(callback, ms){
    clearTimeout (timer);
    timer = setTimeout(callback, ms);
  };
})();

但它仍然没有考虑延迟,只是在mouseenter上立即执行菜单代码。

如何做到这一点?

您似乎在寻找一个常规的setTimeout,它会延迟您放入其中的任何代码的执行。

menubar.on('mouseenter', 'li.parent.level0', function() {
    setTimeout(function() {
        // ... function body
    },2000);
});

只需使用setTimeout:

menubar.on('mouseenter', 'li.parent.level0', function() {
    setTimeout(function() {
        // Do the work here
    }, 2000);
});

如果他们在元素激发之前离开,你可能想取消:

var menubarMouseEnterTimerHandle = 0;
menubar
    .on('mouseenter', 'li.parent.level0', function() {
        clearTimeout(menubarMouseEnterTimerHandle); // Just in case, but we shouldn't get repeated mouseenters...
        menubarMouseEnterTimerHandle = setTimeout(function() {
            // Do the work here
        }, 2000);
    })
    .on('mouseleave', 'li.parent.level0', function() {
        clearTimeout(menubarMouseEnterTimerHandle);
        menubarMouseEnterTimerHandle = 0; 
    });

请注意,0是一个无效的定时器句柄,如果句柄是0clearTimeout将忽略对它的调用,因此我们不需要保护对上面clearTimeout的调用: