节点套接字io计时器实现

我正在节点和套接字中创build一个绘图/猜测游戏。 简单地说:我有一个class级, 游戏 (扩展房间)和一个class级(每场10个)。 每轮用户被指定为抽屉,猜测者有45秒的时间来猜测这个单词。

当第一次猜测,如果定时器高于20秒,定时器减less到20秒。

我当然不确定,但是我是这样开始的:

阶级:

function Round(id, game){ var ROUNDTIME = 45, timer = new Date(); this.id = id; this.game = game; this.endTime = timer.setSeconds(timer.getSeconds() + ROUNDTIME); ... } 

class级游戏:

 function Game(){ this.MAX_ROUNDS = 10; this.rounds = []; this.currentRound = null; ... } Game.prototype.start = function(){ this.nextRound; } Game.prototype.nextRound = function(){ if(this.rounds.length <= this.MAX_ROUNDS){ this.currentRound = new Round(this.rounds.length + 1, this); ... } else { this.endGame(); } } Game.prototype.endGame = function(){ ... } 

之后,我有一个循环function,每次提交答案/消息时都会检查答案。 在第一个答案我减less结束时间,直到20秒左。

所以有两个问题:

  1. 这是一个正确的/良好的方法吗?
  2. 我应该如何将其进一步实施到应用程序本身? (setInterval 1秒发射?或简单发射endDate达到?或另一种方式?)

你可以做类似的事情

 function Round(id, game,loseCallbackFn){ var ROUNDTIME = 45, startTime = new Date(); this.id = id; this.game = game; this.endTime = startTime.getTime()+45*1000; this.timerId = setTimeout(loseCallbackFn,45*1000); ... } ... Round.onWrongGuess(){ if((this.endTime-(new Date()).getTime())>20*1000) {// he has more than 20s left clearTimeout(this.timerId); this.timerId = setTimeout(loseCallbackFn,20*1000); ... }else{ loseCallbackFn(); } } ...