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