Business
Jobs
  • About Us
  • Solutions
    • Job Postings
      Post your job and receive qualified candidates in 48h.
    • Candidate Assessments
      500+ technical and psychological tests, plus anti-fraud.
    • Headhunting
      Tailor-made executive search from start to finish.
    • Payroll + EOR
      Payroll dispersal and EOR across 15+ LATAM countries.
  • Pricing
  • Jobs

0

130
Views
How to fix the delay between a user disconnecting and the disconnect event firing on the server with socket.io?

I am trying to build a small lobby system with socket.io, but I recently encountered a problem when a user closes a tab to leave the lobby. I want to have instant (or at least close to instant) feedback on the client-side when the user disconnects from the lobby.

Unfortunately, it always takes about 35 sec between closing a browser tab and the socket.on('disconnect') event firing on the server, which is too long for what I need.

I already did some research and found out, that the connection gets closed instantly when the reason of closure is a transport close or a transport error.

In my case it seems to be a ping timeout, which means that socket.io waits some time until the next package gets sent. If that doesn't happen, the connection will be closed.

So my question now is, why does the ping timeout reason take place here when closing a tab, and how can I change that to a transport close reason?

My current code looks like this:

const path = require('path');
const http = require('http');
const express = require('express');
const socketio = require('socket.io');
const formatMessage = require('./utils/messages');
const {
  userJoin,
  getCurrentUser,
  userLeave,
  getRoomUsers
} = require('./utils/users');

const app = express();
const server = http.createServer(app);
const io = socketio(server);

// Run when client connects
io.on('connection', socket => {
  socket.on('joinRoom', ({ username, room }) => {
    const user = userJoin(socket.id, username, room);

    socket.join(user.room);
    console.log("ROOMS AFTER JOIN: ", io.sockets.adapter.rooms);

    // Send users and room info
    io.to(user.room).emit('roomUsers', {
      room: user.room,
      users: getRoomUsers(user.room)
    });
  });

  // Runs when client disconnects
  socket.on('disconnect', (reason) => {
    const user = userLeave(socket.id);
    console.log("Reason: ", reason)

if (user) {
  // Send users and room info
  io.to(user.room).emit('roomUsers', {
    room: user.room,
    users: getRoomUsers(user.room)
  });
}
  });
});

const PORT = process.env.PORT || 3000;

server.listen(PORT, () => console.log(`Server running on port ${PORT}`));
about 4 years ago · Juan Pablo Isaza
Answer question
Find remote jobs

Discover the new way to find a job!

Top jobs
Top job categories
Business
Post vacancy Pricing Sales
Legal
Terms and conditions Privacy policy
© 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Show me some job opportunities
There's an error!