Javascript while循环等待增量而不是成为无限循环

时间:2017-07-05 23:37:34

标签: javascript while-loop websocket socket.io nested-loops

现在我的nodejs socket.io'游戏'我想循环浏览目前在线的所有用户*,每个人都有机会成为领导者并点击一个按钮,顺序让下一个用户成为领导者(到,再次,单击一个按钮,使下一个用户成为领导者。你明白了。)我的问题是,当我使while循环等待'leader'套接字触发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. 
        });
    }

1 个答案:

答案 0 :(得分:0)

你不能在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);