Last active
July 24, 2018 05:31
-
-
Save XavierGeerinck/3f633ce5bcb8cb1db645c1baef856277 to your computer and use it in GitHub Desktop.
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
// ======================================================= | |
// 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