setTimeout function is not working as per the expectations. Here's my code:
$(document).delegate('.pur','click', function(e){
var productid = $(this).attr('id');
var quantity = $('#qua').val();
if(quantity>0){
this.value='Adding';
}
else{
this.value='Min 100';
setTimeout(function(){this.value='Buy now'}, 3000);
}
});
Above code doesn't work at all, it doesn't change the value after 3 seconds as it's expected to do. Any flaw or something in it? Can anyone help finding what's wrong with it?
setTimeout function is not working as per the expectations. Here's my code:
$(document).delegate('.pur','click', function(e){
var productid = $(this).attr('id');
var quantity = $('#qua').val();
if(quantity>0){
this.value='Adding';
}
else{
this.value='Min 100';
setTimeout(function(){this.value='Buy now'}, 3000);
}
});
Above code doesn't work at all, it doesn't change the value after 3 seconds as it's expected to do. Any flaw or something in it? Can anyone help finding what's wrong with it?
Share Improve this question edited Jun 19, 2014 at 18:40 j08691 208k32 gold badges269 silver badges280 bronze badges asked Jun 19, 2014 at 18:32 Guy in the chairGuy in the chair 1,0651 gold badge14 silver badges45 bronze badges 3-
2
see here, same issue. The problem is the scope of
this
, you should create a reference to it outside of thesetTimeout
– Austin Greco Commented Jun 19, 2014 at 18:35 -
2
The problem is that the value of
this
in the function you pass tosetTimeout()
won't be what you want it to be. – Pointy Commented Jun 19, 2014 at 18:35 - Yes, got it, problem solved, please make it your answer :) – Guy in the chair Commented Jun 19, 2014 at 18:37
3 Answers
Reset to default 5Scoping issue
inside your setTimeout, "this" doesn't refer to the same object as outside setTimeout.
Fix it like this
$(document).delegate('.pur','click', function(e){
var productid = $(this).attr('id');
var quantity = $('#qua').val();
if(quantity>0){
this.value='Adding';
}
else{
this.value='Min 100';
var that = this; // hold a reference to "this" as "that"
setTimeout(function(){that.value='Buy now'}, 3000); // use "that" instead of "this"
}
});
The reference to "this" in the anonymous function does not point to anything. You could change it like this (i.e., self
being a variable in the visibility scope of your anonymous function):
this.value='Min 100';
var self = this;
setTimeout(function(){self.value='Buy now'}, 3000);
This should also do the trick
setTimeout(function() { this.value = 'Buy now'; }.bind(this), 3000)