[英]Converting a jQuery setInterval timing into a recursive setTimeout timing
我這里有一個隊列管理系統的代碼段,該代碼段根據允許在屏幕上顯示的窗口數從數據庫動態獲取數據。
var elementArray;
function fetchPayment() {
elementArray = new Array();
$('.win_id').each(function() {
// here's the moneyshot
elementArray.push(this);
});
doAjax(0);
}
function doAjax(param) {
if (typeof elementArray[param] === 'undefined') {
var win_id = 0;
} else {
var win_id = elementArray[param].value;
}
$.ajax({
type: "GET",
dataType: 'json',
// async: false,
url: "<?php echo base_url();?>queue/getCurrentTransaction/" + win_id,
success: function(data) {
param++;
if (param <= elementArray.length) {
$('.names-' + win_id).empty();
$('.names-' + win_id).append("<div class='pname'>" + data.customer_name + '<li>' + data.ref_code + '</li></div>');
doAjax(param);
} else {
console.log("!");
}
},
error: function(data) {
param++;
$('.names-' + win_id).empty();
$('.names-' + win_id).append("<div class='pname'><li></li></div>");
doAjax(param);
}
});
}
這行得通,但是,它占用了過多的CPU資源,並且這無疑是一種不好的方法,我重構了其他函數以使其如下所示:
(function fetchNewServiceConnection() {
setTimeout(function() {
$.ajax({
type: "GET",
dataType: 'json',
url: "<?php echo base_url();?>queue/getCurrentTransaction/" + 100,
success: function(data) {
$('.c_name').empty();
$('.c_name').append(data.customer_name + '<li>' + data.ref_code + '</li>');
fetchNewServiceConnection()
},
error: function(data) {
$('.c_name').empty();
$('.c_name').append('<li></li>');
fetchNewServiceConnection()
}
});
}, 500);
})();
這工作快得多。 問題是上面的代碼,如何將其轉換為下面的代碼片段?
在你里面
function doAjax(param) {
if (typeof elementArray[param] === 'undefined') {
var win_id = 0;
} else {
var win_id = elementArray[param].value;
}
$.ajax({
type: "GET",
// etc....
}
你有doAjax(param);
在兩個地方,一個代表success:
一個代表error:
替換
doAjax(param);
在兩個地方都有:
setTimeout(doAjax.bind(null, param), 500);
注意:
我不確定,但是看來您正在嘗試"real time data"
,所以我的建議是查看WebSockets
( https://developer.mozilla.org/en-US/docs/Web/API / WebSockets_API ),托管您自己的提供商,或者最終托管類似Pusher.com( https://pusher.com/ )的提供商
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.