2016-11-07 29 views
0

我有一個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上立即執行菜單代碼。

如何做到這一點?

回答

0

你似乎在尋找的是一個普通的setTimeout,它會延遲你放在它裏面的任何代碼的執行。

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

只需使用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以上: