[英]code gets executed before the specified setTimeout
下面是我的代碼:我希望在指定的時間段后執行代碼行,但它會在超時之前執行它們。
如何確保他們在執行指定的時間之前等待?
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
});
我試圖在超時時進行回調,但無濟於事:
timeout = setTimeout(2000,funciton(){
//after 2sec starts
$(this).attr("data-price",dInput);
shoppingCart.setPriceForItem(dInput,id);
displayCart();
//after 2sec ends
});
setTimeout
的正確配置文件是setTimeout(function,milliseconds,param1,param2,...)
。 在您的代碼中,將毫秒放在函數之前。 嘗試這個:
timeout = setTimeout(function(){
//after 2sec starts
$(this).attr("data-price",dInput);
shoppingCart.setPriceForItem(dInput,id);
displayCart();
//after 2sec ends
}, 2000);
setTimeout()函數具有以下形式
setTimeout(function(){ alert("Hello"); }, 3000);
您的代碼:
timeout = setTimeout(function(){
//after 2sec starts
$(this).attr("data-price",dInput);
shoppingCart.setPriceForItem(dInput,id);
displayCart();
//after 2sec ends
},2000);
這個怎么樣?
$(this).attr("data-price",dInput);
shoppingCart.setPriceForItem(dInput,id);
setTimeout(function(){ displayCart(); }, 2000);
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.