Skip to content

Instantly share code, notes, and snippets.

@joeczar
Last active June 29, 2020 07:00
Show Gist options
  • Select an option

  • Save joeczar/8cc59879b23a508d4ba437f997a047e6 to your computer and use it in GitHub Desktop.

Select an option

Save joeczar/8cc59879b23a508d4ba437f997a047e6 to your computer and use it in GitHub Desktop.
/*
When a countdown instance is created, it should emit a secondElapsed event every second until it gets to zero,
passing the current number of seconds remaining to any listeners that have been added
*/
const events = require("events");
module.exports = class Countdown extends events.EventEmitter {
constructor(num) {
super();
this.timeLeft = num;
this.interval()
}
interval() {
const int = setInterval(() => {
if (this.timeLeft < 0) {
clearInterval(int);
return 0;
}
this.emit("secondElapsed", this.timeLeft--);
}, 1000);
}
};
/*
In index.js, require the countdown module and create an instance of Countdown that counts down from 10.
Add to the instance a listener for the secondElapsed event that logs to the console the number of seconds
remaining followed by an exclamation point. When the number passed to the event listener is 0, log "lift off!"
to the console instead of the number followed by an exclamation point.
Your index.js should end up something like this:
*/
const Countdown = require("./countdown");
const countdown = new Countdown(10);
countdown.on("secondElapsed", function (timeLeft) {
if (timeLeft > 0) {
console.log(timeLeft);
} else {
console.log("lift off!");
}
});
@joeczar
Copy link
Author

joeczar commented Jun 28, 2020

I notice when I run this that the timing inst as good as when I pass in the setInterval through a countdown.emit('secondsElapsed', countdown.interval) in index.js.

@joeczar
Copy link
Author

joeczar commented Jun 29, 2020

I figured out that I was calling setInterval once a second, which was causing the strange timing issue. I fixed that but I am still looking for feedback as to how I can improve it. I'm not very confident about my setInterval function.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment