防止Javascript函数多次触发 [英] Prevent Javascript function from firing multiple times

查看:562
本文介绍了防止Javascript函数多次触发的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

jsFiddle
我使用一个自定义的下拉菜单,该菜单可在jquery事件和动画上运行.
当我通过mouseenter多次激活下拉菜单时,会出现问题,导致菜单先滑后滑几次.我尝试通过添加.stop(true)来解决此问题,该方法很成功,但是它导致了其他问题,例如 jsFiddle Here ),但是它引起了更多没有吸引力的问题.

我需要一种方法来阻止功能重复触发,但仍然能够立即停止向下滑动",如果用户触发.mouseleave,则可以立即向上滑动"

我与自定义队列纠缠了5个小时,但没有成功:(
欢迎任何想法,建议和批评.

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.

推荐答案

基本上可以归结为延迟事件处理程序的执行.

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

如果在指定的时间间隔内调用了相同的处理程序,则挂起的执行将被取消,并在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.

这篇关于防止Javascript函数多次触发的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆