The multiples firing click of Jquery


For thoses who have previously written several scripts with jQuery, one day or another, the problem of a multiples firing event on a click / hover / scroll or other trigger function has happen. Until today, I could not find a decent solution on a search engine nor in the bible of the jQuery problem/solution, stackoverflow

Let's take somes of the solutions proposed

stopPropagation()

stopImmediatePropagation()

unbind()

one()

off()

... multiple other solutions...

If somes of thoses seems work at the first shot, it may later one, show somes weakness as time to time, run multiples time a event or do work with some browser but not with other one or not working with some part of your script, but no problem with other part etc etc...

Let's take a simple example, as a website menu with submenu that show when a click event is firing multiples times. For make the problem happen, click multiples times, as faster as you can for few seconds on "Download" and see :

Jsfiddle multiples firing problem

The submenu after the last click, will continue to slideDown and slideUp as long all the click has not finish to execute the event jQuery. In many case as for hover / scroll / click event, one click could be firing multiples times, disturbing the use of your web application

If all the solutions you previously tried aren't exacly working without problem or doesn't fit for you requirement, here a simple and efficient solution that will prevent the event to firing again or to be add in queue as long a event is running and not yet finish. On this jsfiddle, try as previously, click multiples times for few seconds as fast as possible

Jsfiddle multiples firing solution

The submenu will stop after your last click, no matter of many time you have firing the event. As you can see, we add a boolean variable set to false, when a click is firing the event, we first check the the boolean, if it's false, then, right after we set the the variable to true and allow the event to continue his instruction, at the last part of the event, we add promise().done that will set the boolean to false when only the end of the last instruction have terminated. If the event click is running and another click firing is made, as the check of the boolean at the beginning of the function will be true, it will stop at this point.