Last active
June 29, 2020 07:00
-
-
Save joeczar/8cc59879b23a508d4ba437f997a047e6 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
| /* | |
| 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); | |
| } | |
| }; |
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
| /* | |
| 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!"); | |
| } | |
| }); |
Author
Author
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
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.