Skip to content

Instantly share code, notes, and snippets.

@newbenhd
Last active September 25, 2023 04:25
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save newbenhd/e697c272e2f53ba9f65859e0c7725f97 to your computer and use it in GitHub Desktop.
Save newbenhd/e697c272e2f53ba9f65859e0c7725f97 to your computer and use it in GitHub Desktop.
ticker event emitter factory
/**
* 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