Question

Description of Problem (Fiddle):

I'm attempting to clear multiple instances of a variable being created with setInterval through a mousedown event on a class. In the example provided, if you click the black box only once, a kitten will flash twice and then the variable will be unset.

If you click the black box multiple times in the span of 5 seconds, multiple instances of the kitten will appear, and subsequent clicks will never be removed. Why doesn't clearing red wipe all instances of the variable?

I know I can accomplish 'locking' out clicks by setting a flag, but is there a more elegant way to tackle this, perhaps utilizing this or some other fancy structure? And what are these subsequent variables named if not red?

Code:

var red;

$('.container').mousedown(function() {
    red = window.setInterval(function() {
        $('<img src="http://placekitten.com/g/25/25" />').appendTo('body').animate({
            'opacity': 0
        }, 1000, function(){ $(this).remove(); });
    }, 2000);

    setTimeout(function() {
        window.clearInterval(red);
    }, 5000);

});
Was it helpful?

Solution

"Why doesn't clearing red wipe all instances of the variable?".

Actually, it does. Your code is very clear, you are only clearing the interval after 5 seconds. So if you click the element 20 times, you will have created 20 intervals. If you only want it to ever fire once, you need to clear the interval before you set a new one.

For example, put this before you set the interval:

window.clearInterval(red);

jsFiddle: http://jsfiddle.net/ngDTV/9/

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top