我有一个匿名轮询函数,它有一个 setTimeout 来每 30 秒启动一次 ajax 调用。然而,匿名函数确实会立即启动,但由于某种原因,ajax 调用不会立即启动,而是仅在 30 秒后启动。我是否错过了诸如立即调用它以立即触发之类的东西?
(function poll() {
console.log('polling called');
setTimeout(function () {
$.ajax({
url: "/server/call",
type: 'GET',
dataType: "json",
timeout: 30000,
success: function (data) {
var currentdate = new Date();
var datetime = "Last Sync: " + currentdate.getDate() + "/" + (currentdate.getMonth() + 1) + "/"
+ currentdate.getFullYear() + " @ "
+ currentdate.getHours() + ":"
+ currentdate.getMinutes() + ":"
+ currentdate.getSeconds();
console.log(datetime);
console.log('call was successful at: ' + datetime);
}
});
},
30000);
})();
日志记录仅在 30 秒后开始,而不是立即开始。 谢谢
最佳答案
如果您正在编写一些轮询函数,则必须在上一个函数完成后发送请求。服务器必须在几秒钟后响应浏览器。此时服务器处理所有其他请求。这是示例:
(function poll() {
console.log('polling called');
$.ajax({
url: "/server/call",
type: 'GET',
dataType: "json",
timeout: 30000,
success: function (data) {
var currentdate = new Date();
var datetime = "Last Sync: " + currentdate.getDate() + "/" + (currentdate.getMonth() + 1) + "/"
+ currentdate.getFullYear() + " @ "
+ currentdate.getHours() + ":"
+ currentdate.getMinutes() + ":"
+ currentdate.getSeconds();
console.log(datetime);
console.log('call was successful at: ' + datetime);
},
complete: function () {
setTimeout(function () {
poll()
}, 200) //do nothing 200ms
}
});
})();
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
关于javascript - 匿名javascript轮询函数不会立即触发setTimeout ajax调用,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/43072497/