php - 将 jQuery setInterval 计时转换为递归 setTimeout 计时
问题描述
我在这里有一个队列管理系统的代码片段,它根据允许在屏幕上显示的窗口数量从数据库中动态获取数据。
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/ )
推荐阅读
- java - 无法使用外部库编译 Spring Boot 应用程序
- c# - 无法从 Docker 中的 .NET CORE Web API 连接到 WCF 服务
- jquery - 禁用特定元素的动画
- r - ggplot组间差异
- java - 使用 Java 8 流过滤内部 Map 的值
- c++ - 需要派生类的动态转换:寻找替代方法
- javascript - JavaScript 中 Scala 视图的等价物
- python - ImageItem 在显示来自相机的帧一分钟后崩溃
- php - 当我尝试使用 $wpdb 变量时,它被认为是空的
- python - 如何从多个 excel 文件中获取数据并使用它们创建新工作表