Navigation Menu

Skip to content

Instantly share code, notes, and snippets.

@stuartambient
Last active March 13, 2023 18:55
Show Gist options
  • Star 1 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save stuartambient/7485f29ace060eb6600ca61195d590a6 to your computer and use it in GitHub Desktop.
Save stuartambient/7485f29ace060eb6600ca61195d590a6 to your computer and use it in GitHub Desktop.
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