Reputation: 2466
Below is my code:I expect line of code to be executed after specified time period, but it executes them before the timeout.
How can I ensure they wait for the specified amount of time before execute it?
var timeout;
$('body').on('input', '.set_price', function() {
if(timeout) {
clearTimeout(timeout);
timeout = null;
}
var dInput = this.value;
var id = $(this).attr("data-id");
timeout = setTimeout(2000)
//after 2sec starts
$(this).attr("data-price",dInput);
shoppingCart.setPriceForItem(dInput,id);
displayCart();
//after 2sec ends
});
I tried making callback on timeout like this to no avail:
timeout = setTimeout(2000,funciton(){
//after 2sec starts
$(this).attr("data-price",dInput);
shoppingCart.setPriceForItem(dInput,id);
displayCart();
//after 2sec ends
});
Upvotes: 0
Views: 51
Reputation: 1356
How about this?
$(this).attr("data-price",dInput);
shoppingCart.setPriceForItem(dInput,id);
setTimeout(function(){ displayCart(); }, 2000);
Upvotes: 1
Reputation: 32354
The setTimeout() function has the following form
setTimeout(function(){ alert("Hello"); }, 3000);
your code:
timeout = setTimeout(function(){
//after 2sec starts
$(this).attr("data-price",dInput);
shoppingCart.setPriceForItem(dInput,id);
displayCart();
//after 2sec ends
},2000);
Upvotes: 1
Reputation: 4977
The correct profile for setTimeout
is setTimeout(function,milliseconds,param1,param2,...)
. In your code you put the milliseconds before the function. Try this:
timeout = setTimeout(function(){
//after 2sec starts
$(this).attr("data-price",dInput);
shoppingCart.setPriceForItem(dInput,id);
displayCart();
//after 2sec ends
}, 2000);
Upvotes: 2