Skip to content

Instantly share code, notes, and snippets.

@uudashr
Created October 13, 2017 04:17
Show Gist options
  • Save uudashr/8d1d74e30b815c3a0eec634a737fdb9b to your computer and use it in GitHub Desktop.
Save uudashr/8d1d74e30b815c3a0eec634a737fdb9b to your computer and use it in GitHub Desktop.
Delaying events
function timeout(millis) {
return new Promise((resolve, reject) => {
setTimeout(resolve, millis);
});
}
class Dispatcher {
constructor() {
this.listeners = [];
this.delayedListeners = [];
this.delayedEvents = [];
}
fireEvent(payload) {
const event = {payload: payload, occuredTime: new Date()};
this.listeners.forEach(f => f(event)); // notify all listeners
this._fireDelay(event);
}
_fireDelay(event) {
this.delayedEvents.push(event);
timeout(500).then(() => {
const delayedEvents = this.delayedEvents;
this.delayedEvents = [];
if (delayedEvents.length > 0) {
this.delayedListeners.forEach(f => f(delayedEvents));
}
})
}
onAllEvent(callback) {
this.delayedListeners.push(callback);
}
onEvent(callback) {
this.listeners.push(callback);
}
}
const dispatcher = new Dispatcher();
// dispatcher.onEvent(event => console.log('onEvent:', event));
dispatcher.onAllEvent(events => console.log('onAllEvent:', events));
console.log('Firing events');
timeout(10).then(() => dispatcher.fireEvent('a.txt'));
timeout(200).then(() => dispatcher.fireEvent('b.txt'));
timeout(300).then(() => dispatcher.fireEvent('c.txt'));
timeout(700).then(() => dispatcher.fireEvent('d.txt'));
timeout(1500).then(() => dispatcher.fireEvent('e.txt'));
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment