我的页面上有很长的轮询请求。服务器端的脚本在20秒后设置为超时。多个AJAX请求相互延迟
所以,当长轮询是“闲置”,并且用户按下另一个按钮时,发送该新请求将被延迟,直到前一个脚本超时为止。
我看不出jQuery端的代码有什么问题。为什么onclick事件延迟?
function poll()
{
$.ajax({
url: "/xhr/poll/1",
data: {
user_id: app.user.id
},
type: "POST",
dataType: "JSON",
success: pollComplete,
error: function(response) {
console.log(response);
}
});
}
function pollComplete()
{
poll();
}
function joinRoom(user_id)
{
$.ajax({
url: "/xhr/room/join",
dataType: "JSON",
type: "POST",
data: {
user_id: app.user.id,
room_id: room.id
}
});
}
<button id="join" onclick="javascript:joinRoom(2);">Join</button>
############ PHP Controller on /xhr/poll
$time = time();
while ((time() - $time) < 20)
{
$updates = $db->getNewStuff();
foreach ($updates->getResult() as $update)
$response[] = $update->getResponse();
if (!empty($response))
return $response;
else
usleep(1 * 1000000);
return 'no-updates';
}
“睡眠”是否会成为问题?
问题是否在localhost中? –
用于AJAX调用的PHP代码是否使用会话? –