Skip to content

Instantly share code, notes, and snippets.

Embed
What would you like to do?
NodeJS Design Patterns (third edition) challenges
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