There is an application on expressJS. When I turn to a specific page, an event is launched on the server and with the help of setInterval we send some data to the client. But here, the user closes the page, and the event on the server continues to work. You need to somehow understand how many clients are subscribed to the current event, and if zero, then stop setInterval .

How to do it?

    1 answer 1

    Cancel setInterval

    In addition to setInterval there is a clearInterval that allows you to cancel the execution:

     const intervalId = setInterval(/*...*/); // Начинаем периодическое выполнение clearInterval(intervalId); // и останавливаем его. 

    There are similar functions for setTimeout and setImmediate .

    Definition of user care

    For each disconnection of a user, the corresponding socket creates a disconnect event. Sample code is in this answer .

    Together

    In the simplest case, remember the interval ID and the number of subscribing users. Change the amount when you subscribe or unsubscribe from the newsletter:

    • user connection - count += 1 ;
    • user exit - count -= 1 .

    For each change, check:

    • count 0 - make clearInterval ;
    • count was 0, and became 1 - do setInterval .
     let usersSubscribed = 0; let intervalId = null; io.on('connection', function (socket) { usersSubscribed += 1; if (usersSubscribed === 1) intervalId = setInterval(/*...*/); socket.on('disconnect', function () { usersSubscribed -= 1; if (usersSubscrbied === 0) clearInterval(intervalId); }); }); 
    • Yes, it is clear. But how to understand how many clients are subscribed to a specific event? Or, I thought through the namespace in socket.io to do, but the same question is how to understand how many clients have a particular namespace ? Or maybe it makes sense to do it all through the room ? - sanu0074
    • @ sanu0074 add sockets to an array when connecting or subscribing. - Aleksei Zabrodskii
    • Is there something like onSubscribe ? - sanu0074
    • @ sanu0074 has a list of clients at stackoverflow.com/a/6967755 - Aleksei Zabrodskii
    • NOTE: This Solution ONLY works with version prior to 1.0 - sanu0074