I have some code that polls a service and I need a way to cancel that interval clearTimeout
via events. The timeouts act as an interval, calling setTimeout again within the function.
So for example, I have another object that that's exposed as an event emitter and this process polls and emits some data along the way. Here's a simplified example:
function events() {
var timer = true;
events.on('cancel', function() {
timer = false;
});
function polling() {
//Get some data
events.emit('data', data);
if (timer || typeof timer == 'number') {
timer = setTimeout(polling, 1000);
}
}
polling();
}
This can work, basically when this service receives the cancel
event, it sets the timer to false, which due to the check it won't continue. However, there could be a chance where it passed the condition, event fired, timer reset and now it continues on.
Any idea if there's a more bulletproof way to handle this kind of thing? Basically canceling the polling based on an event.
I have some code that polls a service and I need a way to cancel that interval clearTimeout
via events. The timeouts act as an interval, calling setTimeout again within the function.
So for example, I have another object that that's exposed as an event emitter and this process polls and emits some data along the way. Here's a simplified example:
function events() {
var timer = true;
events.on('cancel', function() {
timer = false;
});
function polling() {
//Get some data
events.emit('data', data);
if (timer || typeof timer == 'number') {
timer = setTimeout(polling, 1000);
}
}
polling();
}
This can work, basically when this service receives the cancel
event, it sets the timer to false, which due to the check it won't continue. However, there could be a chance where it passed the condition, event fired, timer reset and now it continues on.
Any idea if there's a more bulletproof way to handle this kind of thing? Basically canceling the polling based on an event.
Share Improve this question asked Sep 15, 2015 at 21:37 dzmdzm 23.6k50 gold badges152 silver badges229 bronze badges 1-
Instead of setting
timer
to false, how about callingclearTimeout(timer)
? – bardzusny Commented Sep 15, 2015 at 21:42
1 Answer
Reset to default 13However, there could be a chance where it passed the condition, event fired, timer reset and now it continues on.
Nope. Node.js is single-threaded and works by means of an event loop, so nothing can interrupt your running code unless you allow it to (by queuing up and continuing execution in another event, e.g. with setTimeout
or process.nextTick
).
What you should do instead if you want to avoid one more call of polling
, though, is use clearTimeout
.
function events() {
var timer = null;
events.on('cancel', function() {
clearTimeout(timer);
});
function polling() {
//Get some data
events.emit('data', data);
timer = setTimeout(polling, 1000);
}
polling();
}