【发布时间】:2017-07-05 23:37:33
【问题描述】:
现在在我的 nodejs socket.io“游戏”中,我想循环浏览当前在线的所有用户*,每个用户都有机会成为领导者,然后单击一个按钮,依次使下一个用户成为领导者(到,再次,单击一个按钮,使下一个用户成为领导者。你明白了)。我的问题是,当我让 while 循环等待“领导者”套接字触发 leaderSelection 事件以增加 while 循环时,while 循环反而会创建一个无限循环,使我的浏览器崩溃。简单地说,我怎样才能让一个while循环等待(理论上无限的时间)直到它增加,而不是无限运行。希望这已经足够清楚了。这是我的代码:
while(i < ids.length) { //Go through all ids one by one
//Select current id and make that person the leader
socket.broadcast.to(ids[i]).emit('leader', { message: 'You are the leader for this round', options: 'THIS WOULD BE A SELECTION BUTTON FOR THE leaderSelection EVENT LISTENER'});
//Loop through all the other people that are not the leader and say they are the users for this round
for(var e = 0; e < ids.length; e++) {
if(i == e) { //Skip current leader
console.log('skipped ' + usernames[i]);
continue;
}
socket.broadcast.to(ids[e]).emit('user', { message: 'You are a user for this round'});
}
//When the leader socket clicks the 'select' button, the while loop will go to the next person to be a leader
socket.on('leaderSelection', function(data) {
i++; //Here is the issue, the while loop crashes my browser trying to wait for the increment.
});
}
【问题讨论】:
-
你不能那样做。
-
从根本上说,问题是你陷入了僵局。浏览器 Javascript 是单线程的。当您的
while循环正在进行时,不会发生其他任何事情,甚至不会发生leaderSelection回调。所以你的循环不能结束,因为回调没有发生,回调也不能发生,因为循环还没有结束。 -
除了您的
while循环将永远存在之外,您还每次通过while循环添加一个新的socket.on()事件处理程序。您只是不能在 Javascript 中使用这种类型的结构。您看起来不会在 Javascript 中检查某些内容。相反,您注册事件处理程序,响应这些事件并检查这些事件处理程序中的状态。最坏的情况是,您可能会检查计时器上的某些状态。
标签: javascript while-loop websocket socket.io nested-loops