Last active
September 25, 2023 04:25
-
-
Save newbenhd/e697c272e2f53ba9f65859e0c7725f97 to your computer and use it in GitHub Desktop.
ticker event emitter factory
This file contains 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
/** | |
* Write a function that accepts a number an 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. | |
*/ | |
module.exports = function ticker(number, cb) { | |
const ee = new (require('events').EventEmitter)() | |
let count = 0 | |
ee.on('tick', function(time) { | |
if (time > number) return cb(null, count) | |
setTimeout(function() { | |
ee.emit('tick', time + 50) | |
count++ | |
}, 50) | |
}) | |
process.nextTick(ee.emit.bind(ee, 'tick', 0)) | |
return ee | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment