杀死一个“个性化”的间隔

我制作了这个系统,用户可以login到我的网站,玩一个需要间隔时间的游戏。 当用户完成播放,我基本上想要杀死间隔。 虽然一切似乎都运行良好,但杀间隔时间有点不妥。

这里是问题每当一个用户完成播放的时间间隔被杀害,不仅为用户播放,而且为每个人 。 这可能是因为我正在为这个时间间隔分配一个variables,而当一个用户完成一个游戏时,我正在杀死这个interval ,那么我是对的,那么它会杀死其他的时间间隔呢?

这里是我为这个问题写的一些代码,

 var user; //this is a variable that has all info about the user. (its not usually empty) var usersPlaying = []; socket.on('game', function(game) { if(game.type == "start"){ usersPlaying.push({ user_id: user.id }); var game = setInterval(function(){ if(findUser(user.id) !== undefined){ console.log('Second passed!'); }else{ clearInterval(game); //stop the interval } }, 1000); }else if(game.type == "stop"){ console.log("User has decided to quit playing the game!"); usersPlaying.splice(usersPlaying.findIndex(user => user === user.id), 1); //remove user from playing } }); 

自从我重写和简化了代码之后,可能会出现一些错误,否则将是难以帮助我的。

无论如何,我怎么能这样做,它只能清除一个特定的人的时间间隔?

谢谢!

setInterval调用返回一个唯一的ID。 您可以使用该ID来清除间隔计时器:

 var uniqueId = setInterval(function () { /* ... */ }, 1000); 

稍后的 …

 clearInterval(uniqueId); 

会杀死那个特定的定时器。

我build议存储usersPlaying数组内的每个用户的usersPlaying

将特定套接字的时间间隔存储在自己的范围内:

 var user; //this is a variable that has all info about the user. (its not usually empty) var usersPlaying = []; socket.on('game', function(game) { if(game.type == "start"){ usersPlaying.push({ user_id: user.id }); socket.game = setInterval(function(){ if(findUser(user.id) !== undefined){ console.log('Second passed!'); }else{ clearInterval(socket.game); //stop the interval } }, 1000); }else if(game.type == "stop"){ console.log("User has decided to quit playing the game!"); usersPlaying.splice(usersPlaying.findIndex(user => user === user.id), 1); //remove user from playing } }); 

所以你也可以在发生断线时把它杀掉:

 socket.on('disconnecting',function(){ if(socket.game){clearInterval(socket.game);} }); 

编辑:

 var user; //this is a variable that has all info about the user. (its not usually empty) 

更好地将所有内容存储在套接字的范围内(服务器中的每个客户端套接字对象将拥有自己的“用户”键,而不是使用丑陋的全局variables

因此,将其存储为socket.user = {id:"foo"} ,您可以访问该客户端执行套接字事件请求的特定用户对象,如if(findUser(socketuser.id) !== undefined){