javascript - Node 套接字io定时器实现

标签 javascript node.js socket.io socket.io-1.0

我正在 Node 和套接字中创建一个绘图/猜测游戏。 简单地说: 我有一个Room类、Game(扩展了Room)和一个Round类(每场游戏10个)。 每轮都会分配一个用户作为抽屉,猜测者有 45 秒的时间来猜测单词。

第一次猜测计时器是否高于 20 秒时,计时器将减少至 20 秒

我不确定,但这就是我开始的方式:

类(class)回合:

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

类游戏:

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(){
  ...
}

之后,我有一个 Round 函数,每次提交答案/消息时都会检查答案。第一次回答后,我将 endTime 减少到还剩 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();
    }
}
...

关于javascript - Node 套接字io定时器实现,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/26375884/

相关文章:

node.js - passport-facebook - 无法获取 about_me 和电子邮件个人资料字段

angularjs - 在 $http.post 之后用 $http.get 重新加载 Controller

javascript - Python 中的 Web 套接字(使用 flask )问题

javascript - 如何在 Chrome 扩展程序中的函数之间发送变量?

javascript - 如何在 ie7 中使用 jquery 启用禁用的单选按钮

node.js - gcloud app deploy 不会删除以前的版本

Java Socket 不向服务器发送消息

node.js - 如何在 NodeJS 上访问 socket.io 中的 cookie-session 中间件?

javascript - 根据服务变量更改 CSS

javascript - 当屏幕上可见时,进度条圆圈应该开始填满