[英]timeout for function (jQuery)
function getNames(){
// some code
}
此功能可以在一秒鍾內完成,但有時它會在無限時間內凍結自身和頁面上的html塊(內部為ajax)。
我想要此功能有時間限制。 如果十秒內仍未完成,請中止它。
這個怎么做?
使用jQuery 1.5的Promise確實很容易。
下面的示例創建一個Deferred並設置兩個基於計時器的函數以在隨機間隔后解析或拒絕 Deferred。 誰首先觸發“獲勝”並調用其中一個回調。 第二個超時無效,因為從第一個超時操作開始,延遲已完成(處於已解決或已拒絕狀態)。
// Create a Deferred and return its Promise
function asyncEvent() {
var dfd = new jQuery.Deferred();
setTimeout(function() {
dfd.resolve('hurray');
}, Math.floor(Math.random() * 1500));
setTimeout(function() {
dfd.reject('sorry');
}, Math.floor(Math.random() * 1500));
return dfd.promise();
}
// Attach a done and fail handler for the asyncEvent
$.when( asyncEvent() ).then(
function(status) {
alert( status + ', things are going well' );
},
function(status) {
alert( status + ', you fail this time' );
}
);
您可以輕松修改此示例以適合您的需求:
// Create a Deferred and return its Promise
function asyncEvent() {
var dfd = new jQuery.Deferred();
// Your asynchronous code goes here
// When the asynchronous code is completed, resolve the Deferred:
dfd.resolve('success');
setTimeout(function() {
dfd.reject('sorry');
}, 10000); // 10 seconds
return dfd.promise();
}
// Attach a done and fail handler for the asyncEvent
$.when( asyncEvent() ).then(
function(status) {
alert( status + ', things are going well' );
},
function(status) {
alert( status + ', you fail this time' );
}
);
如果是函數本身正在逐漸消失,則只需設置一個計時器,然后在超過最大時間段時return
或throw
。
另一方面,如果延遲是由於AJAX請求未返回而引起的,並且您正在使用$.ajax()
,則可以始終設置timeout
設置。 它應該終止請求。 請注意,您需要避免依賴success
回調,因為只有在請求成功時才調用success
回調。 而是,使用complete
回調來監視失敗。 它會告訴您是否發生錯誤。 根據文檔,此功能從1.4開始可用。 我不確定1.4之前的版本,但我認為它也適用於1.3。
如上所述,如果某些代碼有時可能需要很長時間(例如,等待來自慢速服務器的大量信息),則可以使用Web Workers。 這樣就可以在不鎖定主頁的情況下進行后台處理。 請注意,並非所有瀏覽器都支持它。
您可以在這里找到不錯的介紹。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.