Last active
March 13, 2023 18:55
-
-
Save stuartambient/7485f29ace060eb6600ca61195d590a6 to your computer and use it in GitHub Desktop.
NodeJS Design Patterns (third edition) challenges
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
const { EventEmitter } = require('events'); | |
const ticker = (num, cb) => { | |
let timePassed = 0, | |
count = 0; | |
const emitter = new EventEmitter(); | |
const repeat = () => { | |
if (timePassed >= num) return process.nextTick(() => cb(count)); | |
emitter.emit('tick', 'tock'); | |
setTimeout(repeat, 50); | |
process.nextTick(() => (timePassed += 50)); | |
process.nextTick(() => (count += 1)); | |
}; | |
setTimeout(repeat, 50); | |
return emitter; | |
}; | |
const cb = completed => { | |
console.log(`Completed ${completed} ticks`); | |
}; | |
ticker(200, cb) | |
.on('tick', tock => console.log(tock)) | |
.on('completed', x => console.log(x)); |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment