Js Lim
Js Lim

Reputation: 3675

Socket.io in Express JS on connection execute multiple times

I refer this repo to integrate socket.io.

What I want to achieve is, a countdown timer, which send to client every second, setInterval is run on server side. The result I get is

Socket.io & Express JS

The terminal there is on.('connection'), first time I refresh the page, it executed 4 times on.('connection'), the countdown is working fine. Then I refresh 2nd time, it executed 8 times on.('connection'), and the countdown timer also have 2 values there. Then continue.... 12 times, 16 times...

In app.js

app.use(function(req, res, next){
  res.io = io; 
  io.on('connection', function(socket) {
    console.log(socket.id + ' connected.');
  }); 
  next();
});

In routes/users.js

router.get('/', function(req, res, next) {

  models.User.findAll({
    include: [ {model: models.Task, as: 'tasks'} ]
  }).then(function(users) {

    var eventTime= new Date('2017-03-31 13:00:00').getTime();
    var currentTime = new Date().getTime();
    var diffTime = eventTime - currentTime;
    var duration = moment.duration(diffTime*1000, 'milliseconds');
    var interval = 1000;

    setInterval(function() {
      duration = moment.duration(duration - interval, 'milliseconds');
      res.io.emit('countdown', { time_left: duration.hours() + ":" + duration.minutes() + ":" + duration.seconds() }); 
    }, interval);

    res.render('users', {
      title: 'Sequelize: Express Example',
      users: users
    });   
  });   
});

Anything goes wrong here?

Upvotes: 0

Views: 1158

Answers (2)

Js Lim
Js Lim

Reputation: 3675

I found the answer here

io.on('connection', function(socket) {
  socket.removeAllListeners(); <---------- ADD THIS LINE
  console.log(socket.id + ' connected.');
}); 

Upvotes: 5

Amulya Kashyap
Amulya Kashyap

Reputation: 2373

I think you probably your keeping io.on('connection') event within setInterval. That's why it every time keeps on replication in *2.

You can do it like this if you want to achieve countdown timer :

io.on('connection', function (socket){
  var tick = 0;
  setInterval(function(){

    socket.emit('timer', tick++)
  }, 1000);
}) 

Now you can listen to timer event on front-end and display result. Thanks

Upvotes: -1

Related Questions