【问题标题】:Javascript while loop waits for increment instead of becoming an infinite loopJavascript while循环等待增量而不是成为无限循环
【发布时间】: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


【解决方案1】:

您不能在 while 循环中执行此操作,Javascript 不能那样工作。一种可能的替代方法:

// Notify the current leader
function notifyLeader(leader) {
    socket.broadcast.to(leader).emit('leader', { message: 'You are the leader for this round', options: 'THIS WOULD BE A SELECTION BUTTON FOR THE leaderSelection EVENT LISTENER'});
}

// Notify all users except the leader
function notifyUsers(users, leader) {
    users
    .filter(user => user !== leader)
    .forEach(user => {
        socket.broadcast.to(user).emit('user', { message: 'You are a user for this round'});
    });
}

// In a round of play, notify the leaders and users
// When the leaderSelection event comes in, start a new round
// with the next leader
function startRound(ids, leaderIndex) {
    notifyLeader(ids[index]);
    notifyUsers(ids, leaderIndex);
    socket.once('leaderSelection', () => {
        startRound(ids, ++leaderIndex);
    });
}

// Start the first round with leader 0
startRound(ids, 0);

【讨论】:

  • 酷,我会尽快检查一下。只是想承认你并说声谢谢。这看起来很有希望。
猜你喜欢
  • 1970-01-01
  • 2013-02-16
  • 1970-01-01
  • 1970-01-01
  • 2015-07-18
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多