admin管理员组文章数量:1389859
If I want to implement short polling like this:
function firstCall(){
$.ajax({
...
success: function(response){
if (response.OK == "OK"){
secondCall();
}else{
firstCall();
}
}
});
}
Will this be enough? or do I really need to surround the firstCall()
in else clause with setTimeout
?Thanks
If I want to implement short polling like this:
function firstCall(){
$.ajax({
...
success: function(response){
if (response.OK == "OK"){
secondCall();
}else{
firstCall();
}
}
});
}
Will this be enough? or do I really need to surround the firstCall()
in else clause with setTimeout
?Thanks
- 6 How hard do you want to hit your server? This could result in 10+ requests per second. Also, you should handle AJAX errors. – josh3736 Commented Aug 8, 2012 at 13:54
- 1 There are so many good alternatives to this kind of aggressive "are we there yet?" polling. Is this really your only option? – James M Commented Aug 8, 2012 at 13:59
- Oh geesh. Thanks for pointing out. SO obvious. @JamesMcLaughlin Mind to share? – user1012451 Commented Aug 8, 2012 at 14:00
- 1 Comet/long-polling, websockets, ... – James M Commented Aug 8, 2012 at 14:00
4 Answers
Reset to default 5I remend you to use a little timeout, because now you are creating a lot of traffic to your server. Ajax is fast and success
will be executed very often.
So I remend you to use setTimeout or setInterval instead!
This solution relies on the first call to be a success. If at any point in time your code doesn't "succeed" (perhaps there was a server hiccup?), your "polling" will stop until a page refresh.
You could use setInterval
to call that method on a defined interval, which avoids this problem:
setInterval(function(){
$.ajax({}); // Your ajax here
}, 1000);
With both solutions, your server will be handling a lot of requests it might not need to. You can use a library like PollJS (shameless self plug) to add increasing delays, which will increase performance and decrease bandwidth:
// 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");
You need setTimeout()
if you want to reduce requests to server
you'll need to setTimeout if you don't want to wait to user action or ajax response to trigger an event after a certain time, otherwise you may do wait for the ajax call success or error events.
本文标签: javascriptDo we need setTimeout for short pollingStack Overflow
版权声明:本文标题:javascript - Do we need setTimeout for short polling? - Stack Overflow 内容由网友自发贡献,该文观点仅代表作者本人, 转载请联系作者并注明出处:http://www.betaflare.com/web/1744712712a2621221.html, 本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌抄袭侵权/违法违规的内容,一经查实,本站将立刻删除。
发表评论