使用Socket.io的倒数计时器不能与setInterval函数一起使用

时间:2015-06-28 06:18:46

标签: javascript node.js socket.io

正如标题所说,我正在使用Socket.io在Node.js中构建一个倒数计时器。但是setInterval函数中的Socket.io函数无效。

Heres代码:

var app = require('express')();
var http = require('http').Server(app);;
var io = require('socket.io')(http);
io.on('connection',function(socket){
  console.log("a user connected");
  var min = 3;
  var sec = 00;
  var time = new Object;
  function timer()
  {       
    if(sec == 00)
    {
      min = min-1;
      sec = 60;
    }
    if(min == 0)
      {return;}
    sec = sec-1;
    time = {'min':min,'sec':sec};
    console.log("timer working"); //this is working without any problem
    socket.emit('time',"time");
    console.log("after socket working"); // this also works
  }
var starttime = setInterval(timer,1000);
if(min == 0)
{
  clearInterval(starttime);
}

客户方:

socket.on('time',function(time){            
    alert(time);
 });

0 个答案:

没有答案