Get Even More Visitors To Your Blog, Upgrade To A Business Listing >>

Ensuring setInterval does not repeat itself

Ensuring setInterval does not repeat itself

Problem

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);
Problem courtesy of: dzm

Solution

Any suggestions to ensure that a new timer never initiates more than once?

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. Calling setTimeout recursively within its own callback ensures that only one timer event at a time is ever put on the event queue.

Solution courtesy of: Alnitak

Discussion

View additional discussion.



This post first appeared on Node.js Recipes, please read the originial post: here

Share the post

Ensuring setInterval does not repeat itself

×

Subscribe to Node.js Recipes

Get updates delivered right to your inbox!

Thank you for your subscription

×