I’m using Node.js with socket.io and have setInterval for a timer.
I have the following in place. I’m clearing the interval on disconnect and also checking prior to setting the interval. However, If I refresh the page a lot, it seems to not be accurate. The console log will show ‘time’ in intervals much faster than one second and grouped together.
Any suggestions to ensure that a new timer never initiates more than once?
socket.on('disconnect', function () {
console.log('Disconnected');
clearInterval(timer);
});
if (typeof timer != 'undefined') {
clearInterval(timer);
}
var timer = setInterval(function() {
console.log('time');
}, 1000);
That’s exactly what
setTimeout()does…If perhaps you meant “more than once per second“ you need to be aware that
setInterval()will cause events to stack up if they’re not handled in a timely fashion. This will be what’s causing your gaps of less than one second.The only answer to that is to start a new one-shot timer using
setTimeout()from within the timeout handler itself. CallingsetTimeoutrecursively within its own callback ensures that only one timer event at a time is ever put on the event queue.