Skip to content

Instantly share code, notes, and snippets.

@XavierGeerinck
Last active July 24, 2018 05:31
Show Gist options
  • Save XavierGeerinck/3f633ce5bcb8cb1db645c1baef856277 to your computer and use it in GitHub Desktop.
Save XavierGeerinck/3f633ce5bcb8cb1db645c1baef856277 to your computer and use it in GitHub Desktop.
// =======================================================
// Poller.js
// =======================================================
const EventEmitter = require('events');
class Poller extends EventEmitter {
/**
* @param {int} timeout how long should we wait after the poll started?
*/
constructor(timeout = 100) {
super();
this.timeout = timeout;
}
poll() {
setTimeout(() => this.emit('poll'), this.timeout);
}
onPoll(cb) {
this.on('poll', cb);
}
}
module.exports = Poller;
// =======================================================
// index.js
// =======================================================
const Poller = require('./Poller');
// Set 1s timeout between polls
// note: this is previous request + processing time + timeout
let poller = new Poller(1000);
// Wait till the timeout sent our event to the EventEmitter
poller.onPoll(() => {
console.log('triggered');
poller.poll(); // Go for the next poll
});
// Initial start
poller.poll();
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment