Created
August 19, 2025 11:53
-
-
Save vassalloandrea/c3b913686d3f56fc0fa8c191a0a5930b to your computer and use it in GitHub Desktop.
Ticker
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
| // 3.2 Ticker: Write a function that accepts a number and a callback as the | |
| // arguments. The function will return an EventEmitter that emits an event | |
| // called tick every 50 milliseconds until the number of milliseconds is passed | |
| // from the invocation of the function. The function will also call the callback | |
| // when the number of milliseconds has passed, providing, as the result, the total | |
| // count of tick events emitted. Hint: you can use setTimeout() to schedule | |
| // another setTimeout() recursively. | |
| import EventEmitter from 'events'; | |
| function ticker(number, cb) { | |
| let tickCount = 0; | |
| const eventEmitter = new EventEmitter(); | |
| const timer = function (totalMs) { | |
| setTimeout(() => { | |
| eventEmitter.emit('tick'); | |
| tickCount++; | |
| if (totalMs <= 0) { | |
| return cb(tickCount); | |
| } | |
| timer(totalMs - 50); | |
| }, 50); | |
| }; | |
| timer(number); | |
| return eventEmitter; | |
| } | |
| ticker(300, (tickCount) => console.log(`Tick count: `, tickCount)).on('tick', () => console.log('A tick is passed')); |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment