简体   繁体   English

防止Javascript函数多次触发

[英]Prevent Javascript function from firing multiple times

jsFiddle jsFiddle
I use a customized drop-down menu which runs on jquery events and animations. 我使用自定义的下拉菜单,该菜单可在jquery事件和动画上运行。
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. 当我通过mouseenter多次激活下拉菜单时,会出现问题,导致菜单先滑后滑几次。 I tried to fix it by adding .stop(true), which was successful, but it resulted in other problems like this. 我尝试通过添加.stop(true)来修复此问题,该方法很成功,但是却导致了其他类似问题 I followed that advice( jsFiddle Here ), but it causes more unattractive problems. 我遵循了该建议( jsFiddle Here ),但是它引起了更多没有吸引力的问题。

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 我需要的是一种方法,可以防止功能重复触发,但仍然能够立即停止“向下滑动”,如果用户触发.mouseleave,则可以立即“向上滑动”

I tangled with custom queues for a good 5 hours, with no success :( 我纠结了五个小时的自定义队列,但没有成功:(
Any ideas, advice, and criticism is welcome. 欢迎任何想法,建议和批评。

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. 如果在指定的间隔内调用了同一处理程序,则挂起的执行将被取消,并再次排队等待10ms之后执行,以希望在该间隔内没有后续的触发器。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM