Gelunox
Gelunox

Reputation: 792

setTimout screws up variable javascript

I'm having trouble with a piece of script that removes an object X amount of time after it has gotten the class 'hidden'

selector = getselector($(this).parent().parent());
console.log("Clicked Cancel");
$(this).parent().parent().addClass('hidden');
setTimeout(function() {
    $(selector).remove();
}, 400);

I edited some piece of script from here to make function getselector since $(this) doesn't work within a setTimeout. now this piece of code works, as long as you don't run it too quickly again. problem seems to be that variable selector gets messed up when a another node gets deleted within the timespan (currently 400ms)

and I can't think of an easy way around it. :(

Upvotes: 0

Views: 67

Answers (3)

ThiefMaster
ThiefMaster

Reputation: 318518

The answer is simple: Don't make selector global, i.e. use var. Oh, and simply store the element instead of trying to build a selector:

var elem = $(this).parent().parent();
elem.addClass('hidden');
setTimeout(function() {
    elem.remove();
}, 400);

Upvotes: 1

YMMD
YMMD

Reputation: 3780

You can also queue the removal in the following way, which makes your Code a little bit more spicy:

$(this).parent().parent().addClass('hidden').delay(400).queue(function() {
   $(this).remove();
});

Upvotes: 1

Andrius Naruševičius
Andrius Naruševičius

Reputation: 8578

Set a variable with a value true at the start of the process. On action, check whether it is not false and then set it to false and then back to true once finished. If you click it too fast, it will check your variable, see it is true again and will do the action again.

Upvotes: -1

Related Questions