簡體   English   中英

setTimeout的異常行為

[英]Unexpected behavior with setTimeout

我已經實現了一個ajax輪詢功能,該功能需要不斷調用,直到輪詢結果返回我的預期結果為止。 為了實現這一點,我使用setTimeout引入了一個延遲,以便該函數不會僅僅在請求得到結果之前就對服務器進行請求。

首先,我要說的是,我已經找到實現所需代碼以實現所需行為的方式。 但是,我的問題是關於我找到的解決方案。 我想知道為什么該解決方案可以正確處理超時,而另一個解決方案卻不能。

這是成功設置超時並輪詢結果的工作代碼:

function makeRequest(url, data, requestType, successCallback, errorCallback, doneCallback) {
    $.ajax({
        url: url,
        type: requestType,
        data: data != null ? JSON.stringify(data) : '',
        contentType: 'application/json; charset=utf-8',
        success: function (success) {
            if (successCallback) successCallback(success);
        },
        error: function (error) {
            if (errorCallback) errorCallback(error);
        },
        done: function() {
            if (doneCallback) doneCallback();
        }
    });
}

function pollForResult(Id) {
    setTimeout(function () {
        makeRequest('/Transaction/TransactionResult/' + Id,
            null,
            "GET",
            function(result) {
                //success code here
            }, function(error) {
                //error callback implementation here
                if (error.status === 404) {
                    pollForResult(Id); //results not ready, poll again.
                } else {
                    alert("stopped polling due to error");
                }
            }, null);
    }, 2000);
}

下面的代碼沒有正確設置超時,只是不斷地向服務器發送請求:

function pollForResult(Id) {
    makeRequest('/Transaction/TransactionResult/' + Id,
        null,
        "GET",
        function(result) {
            //success code here
        }, function(error) {
            //error callback implementation here
            if (error.status === 404) {
                setTimeout(pollForResult(Id), 2000); //results not ready, poll again.
            } else {
                alert("stopped polling due to error");
            }
       }, null);
}

所以,我的問題是:第二個代碼塊使它不斷輪詢服務器以獲取結果,而不是等待2秒鍾再次輪詢,這是什么?

我懷疑,盡管我沒有嘗試過,但是在第二個代碼塊中它可以正常工作:

setTimeout(function(){ pollForResult(Id); }, 2000); //results not ready, poll again.
setTimeout(pollForResult(transactionId),2000);

此代碼立即調用pollForResult並將其返回值分配為發生超時時調用的函數。

這是理想的行為,因為您可能具有一個構建閉包並將其傳遞給超時的函數。 但是似乎吸引了很多人...

如您所說, function() {pollForResult(transactionId);}可以正常工作。

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM