-
喵喵时光机
function doPoll(){
$.post('ajax/test.html', function(data) {
alert(data); // process results here
setTimeout(doPoll,5000);
});}
-
慕妹3146593
代码片段:(function poll() {
setTimeout(function() {
$.ajax({
url: "/server/api/function",
type: "GET",
success: function(data) {
console.log("polling");
},
dataType: "json",
complete: poll,
timeout: 2000
})
}, 5000);})();这将仅在ajax请求完成后才生成下一个请求。上述内容的变体,将在第一次调用等待/超时间隔之前立即执行。(function poll() {
$.ajax({
url: "/server/api/function",
type: "GET",
success: function(data) {
console.log("polling");
},
dataType: "json",
complete: setTimeout(function() {poll()}, 5000),
timeout: 2000
})})();
-
catspeake
来自ES6,var co = require('co');var $ = require('jQuery');// because jquery doesn't support Promises/A+ specfunction ajax(opts) {
return new Promise(function(resolve, reject) {
$.extend(opts, {
success: resolve,
error: reject });
$.ajax(opts);
}}var poll = function() {
co(function *() {
return yield ajax({
url: '/my-api',
type: 'json',
method: 'post'
});
}).then(function(response) {
console.log(response);
}).catch(function(err) {
console.log(err);
});};setInterval(poll, 5000);不使用递归(函数堆栈不受影响)。在setTimeout-recursion需要尾调用优化的情况下不会受到影响。
-
慕尼黑的夜晚无繁华
function poll(){
$("ajax.php", function(data){
//do stuff
}); }setInterval(function(){ poll(); }, 5000);