I’m trying to make elements appear and disappear with fading animation when the user clicks. I have this working but there is a problem if the user clicks twice in quick succession or before an animation has finished.
I know the problem will be related to the run loop and the timing of the events and animation etc., but as a newbie to html/js I’m not experienced enough with these issues in that context to know the best solution.
Here’s a fiddle, if you click on the first line and wait a few seconds between each click it’ll work, if you click furiously you’ll soon start to see problems.
Thanks
This is a more common issue than you might think. The issue is that you have an event set up to set your element to
display: none. But if you click again, you want to stop that event from taking place. So what you need to do is keep a reference to the event (setTimeout()returns this) so that you can callclearInterval()on that reference if you need to cancel the hiding of the element:Note that I wrapped your listener function inside a larger, immediately invoked function expression that returns the original function. I did this so that
intervalis retained from one call oflistener()to the next. You could also makeintervala global variable, but those are naughty and this solution is much more pleasantly self-contained.Seems to work fine when I swap it into your JSFiddle. Good job with the rest of the code!