2016-11-07 4 views
0

サイトのmenubarでmouseenterイベントを監視するための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); 
}); 

0が無効なタイマーハンドルであることを

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

注意をし、 clearTimeoutは、ハンドルが0の場合はその呼び出しを無視するので、への呼び出しに警備員は必要ありません上記の210:

関連する問題