Change from this:
setTimeout(hide(this),2000);
to this:
var self = this;
setTimeout(function() {
hide(self);
},2000);
You were calling the function immediately and passing its return value to setTimeout
rather than passing a function reference to setTimeout
that can be called later. Keep in mind that (xx)
means execute now. So hide(this)
means to execute it now, not later. On the other hand, function() { hide(this); }
is a function reference that can be called later.
Or, if you aren't using the hide function anywhere else, then you can integrate it in like this:
$(".addtimer div").click(function(){
$(this).toggleClass("remove");
var self = this;
setTimeout(function() {
$(self).remove();
},2000);
});
A useful language feature is .bind()
which can be used to "hardwire" the value of this
or of arguments to callback functions. For example, you could do this:
$(".addtimer div").click(function(){
$(this).toggleClass("remove");
setTimeout(function() {
$(this).remove();
}.bind(this),2000);
});
The .bind(this)
sets the current value of this
to be the value of this
when the callback function is called.
Or, if you still have the function hide(item)
, then you could use .bind to set the argument to hide()
like this:
$(".addtimer div").click(function(){
$(this).toggleClass("remove");
setTimeout(hide.bind(null, this)), 2000);
});
Or, you could use an animation and let it provide the timing for you:
$(".addtimer div").click(function(){
$(this).toggleClass("remove").delay(1000).slideUp(1000, function() {
$(this).remove();
});
});
As you can see, there are lots of options and which to use depends a bit on the situation, what you think makes the clearest code in your situation and what you are most comfortable in using.