Created
August 19, 2025 12:03
-
-
Save vassalloandrea/9ad441630a1bbd8da12dd88adc1fdbf1 to your computer and use it in GitHub Desktop.
Modified 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.3 A simple modification: Modify the function created in exercise 3.2 so that | |
| // it emits a tick event immediately after the function is invoked. | |
| import EventEmitter from 'events'; | |
| function ticker(number, cb) { | |
| const eventEmitter = new EventEmitter(); | |
| // Next tick is needed preventing to unleash Zalgo | |
| process.nextTick(() => { | |
| eventEmitter.emit('tick'); | |
| }); | |
| let tickCount = 0; | |
| eventEmitter.on('tick', () => { | |
| tickCount++; | |
| }); | |
| const timer = function (totalMs) { | |
| setTimeout(() => { | |
| eventEmitter.emit('tick'); | |
| if (totalMs <= 0) { | |
| return cb(tickCount); | |
| } | |
| timer(totalMs - 50); | |
| }, 50); | |
| }; | |
| timer(number); | |
| return eventEmitter; | |
| } | |
| ticker(1000, (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