samedi 27 juin 2015

Countdown timer with socket.io not working with setInterval function

As the title says, iam building a countdown timer in nodejs with socket.io. But the socket.io function inside the setinterval function is not working.

Heres code:

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);
}

Aucun commentaire:

Enregistrer un commentaire