Justin Meltzer Justin Meltzer - 2 years ago 91
Javascript Question

How to override a currently running function if called again in jQuery?

I have this function that is triggered if a user clicks a div. The user can click this div many times, thus triggering the function many times.

Every time the function is called while it is already running, I want the currently running function to stop running and start over. This is hard to describe but I hope it makes sense. Essentially, I want the function to run completely through only if the user does not trigger the function again while it is running.

Is there a way to do this?

Answer Source

Javascript is single threaded. Thus the second clicks will not get processed until the javascript attached to the first click has run to completion.

You can read more about how the javascript event queue works here: How does JavaScript handle AJAX responses in the background?

If you are using asynchronous operations like jQuery animations, then those are run in little pieces off timers and you can get subsequent button presses while an animation is run. In that cause, you would need to stop the animation. With jQuery, you would use the .stop(true, true) method to stop the current animation, advance it to completion and clear it from the queue.

If you include your actual code, we could give a more specific answer for your situation.

Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download