1

I have written a JQuery program that, on the press of a button, runs a dozen or so setTimeout's as well as a few animations. The program operates on existing div's, changes their HTML (using id selectors), fades in, fades out, etc...

The entire process can take up to 15 seconds. The problem is that if the button is pressed again within that time frame then the fade ins and outs start piling on top of each other and looking weird.

Is there something that I can use so that if the button is pressed again then all JQuery stuff in progress just stops and is cleared out? I have tried using clearTimeout, which doesn't seem to work.

gmath
  • 71
  • 6
  • 1
    Post your code here, [stop()](http://api.jquery.com/stop/) could be an option for you `sudowned` already mentioned it. – The Alpha Sep 01 '12 at 23:08
  • Why don't you disable the button and re-enable it when your code finishes? Note that there is a difference between "jQuery stuff" and "JavaScript code you've queued via `setTimeout()`". You would need a combination of `.stop()` for the jQuery animations and `clearTimeout()` for your own code, but `clearTimeout()` can't stop callbacks that have _already_ been called... – nnnnnn Sep 02 '12 at 01:14

1 Answers1

2

You can either use .stop() or .clearQueue().

When the .clearQueue() method is called, all functions on the queue that have not been executed are removed from the queue. When used without an argument, .clearQueue() removes the remaining functions from fx, the standard effects queue. In this way it is similar to .stop(true). However, while the .stop() method is meant to be used only with animations, .clearQueue() can also be used to remove any function that has been added to a generic jQuery queue with the .queue() method.

And you can also prevent the button from doing any actions until the timer is finished. You can put a Boolean variable that after the first click get value of false and when the timer is finished, turn this variable back to true and check for it whenever you click the button.

Community
  • 1
  • 1
Rafael Adel
  • 7,673
  • 25
  • 77
  • 118
  • 1
    Nice. Much more comprehensive than my answer. – Winfield Trail Sep 01 '12 at 23:22
  • I couldn't get the .clearQueue() method to work. It might be because I'm not using .queue() anywhere and mostly using setTimeout. Your idea for stopping the button from working while the program was in progress did help though. I am also looking for a way to put a "cancel" button that would clear all future setTimeouts. It might be that I need to learn how to use queue(). So I reformulated and asked my question again here: http://stackoverflow.com/questions/12237840/how-to-use-queue-with-a-cancel-button – gmath Sep 02 '12 at 16:42