Prevent Javascript function from firing multiple times

萝らか妹 提交于 2019-12-12 05:31:49

问题


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.


回答1:


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.



来源:https://stackoverflow.com/questions/12119107/prevent-javascript-function-from-firing-multiple-times

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!