0

I have a jquery code for observing mouseenter event on menubar in a site.

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

Now I want to provide a delay such that the event function body executes after 2000 ms, something like below:

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

I tried the following:

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

But still it doesn't consider the delay, just executes menu code instantly on mouseenter.

How to do this ?

Vicky Dev
  • 1,893
  • 2
  • 27
  • 62

2 Answers2

0

What you seem to be looking for is a regular setTimeout, which will delay the execution of any code you place inside it.

menubar.on('mouseenter', 'li.parent.level0', function() {
    setTimeout(function() {
        // ... function body
    },2000);
});
adeneo
  • 312,895
  • 29
  • 395
  • 388
0

Just use setTimeout:

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

You might want to cancel that if they leave the element before it fires:

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

Note that 0 is an invalid timer handle, and clearTimeout will ignore a call made to it if the handle is 0, so we don't need guards on the calls to clearTimeout above:

T.J. Crowder
  • 1,031,962
  • 187
  • 1,923
  • 1,875