如果我想实现这样的短轮询:
function firstCall(){
$.ajax({
...
success: function(response){
if (response.OK == "OK"){
secondCall();
}else{
firstCall();
}
}
});
}
这样就足够了吗?或者我真的需要用setTimeout
将else子句中的firstCall()
括起来吗?
发布于 2012-08-08 21:55:32
我建议您使用一点超时,因为现在您正在为您的服务器创建大量流量。Ajax很快,而且success
会经常被执行。
所以我建议你改用setTimeout或setInterval!
发布于 2012-08-08 22:00:01
这个解决方案依赖于第一次调用才能成功。如果在任何时候你的代码没有“成功”(可能是服务器出了点问题?),你的“轮询”将会停止,直到页面刷新。
您可以使用setInterval
在定义的时间间隔内调用该方法,从而避免此问题:
setInterval(function(){
$.ajax({}); // Your ajax here
}, 1000);
使用这两种解决方案,您的服务器将处理许多它可能不需要的请求。你可以使用像PollJS (无耻的self plug)这样的库来增加延迟,这将提高性能并减少带宽:
// Start a poller
Poll.start({
name: "example_poller",
interval: 1000,
increment: 200,
action: function(){
$.ajax({}); // Your ajax here
}
});
// If you want to stop it, just use the name
Poll.stop("example_poller");
发布于 2012-08-08 21:56:27
如果您想减少对服务器的请求,则需要使用setTimeout()
https://stackoverflow.com/questions/11866027
复制相似问题