Skip to content

Instantly share code, notes, and snippets.

@goldbergyoni
Created July 4, 2018 09:02
Show Gist options
  • Select an option

  • Save goldbergyoni/d14f7158202ab3bf764020294b1b0737 to your computer and use it in GitHub Desktop.

Select an option

Save goldbergyoni/d14f7158202ab3bf764020294b1b0737 to your computer and use it in GitHub Desktop.
Realtime event emitters
const EventEmitter = require("events");
class Session extends EventEmitter {
constructor(id) {
super();
this.id = id;
}
start() {
console.log(`Session is about to start ${this.id}`);
const howLongToRun = Math.ceil(Math.random()*5);
setTimeout(() => {
this.emit("end", this.id);
}, howLongToRun*1000);
}
}
class Scheduler {
start() {
[1, 2, 3].forEach((item) => {
const session = new Session(item);
session.on('end', (id) => {
console.log(`Scheduler was notified that session has finished ${id}`);
});
session.start();
console.log(`Scheduler just started session ${item}`)
})
}
}
new Scheduler().start();
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment