Saik
Saik

Reputation: 315

Prevent Javascript function from firing multiple times

jsFiddle
I use a customized drop-down menu which runs on jQuery events and animations.

The problem occurs when I activate the drop-down via mouseenter several times, which results in the menu sliding down then sliding up several times. I tried to fix it by adding .stop(true), which was successful, but it resulted in other problems like this. I followed that advice(jsFiddle Here), but it causes more unattractive problems.

I need is a way to stop a function from firing redundantly, but still be able to stop a "slide down" immediately and then "slide up" if the user triggers .mouseleave.

I tangled with custom queues for a good 5 hours, with no success :(
Any ideas, advice, and criticism is welcome.

Upvotes: 0

Views: 2892

Answers (1)

Robin Maben
Robin Maben

Reputation: 23044

Basically it boils down to delaying the execution of the event handler.

var mouseoverTimer = null;    

$('.elem').mouseover(function(){

   clearTimeout(mouseoverTimer); //ignore previous trigger

   mouseoverTimer  = setTimeout(function(){ //wait to execute handler again
     //execute actual handler here
   }, 10);
});

If the same handler was called within the specified interval the pending execution is cancelled and queued again to execute 10ms later hoping that there's no subsequent trigger within that interval.

Upvotes: 1

Related Questions