Skip to content

Instantly share code, notes, and snippets.

@vassalloandrea
Created August 19, 2025 11:53
Show Gist options
  • Select an option

  • Save vassalloandrea/c3b913686d3f56fc0fa8c191a0a5930b to your computer and use it in GitHub Desktop.

Select an option

Save vassalloandrea/c3b913686d3f56fc0fa8c191a0a5930b to your computer and use it in GitHub Desktop.
Ticker
// 3.2 Ticker: Write a function that accepts a number and 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.
import EventEmitter from 'events';
function ticker(number, cb) {
let tickCount = 0;
const eventEmitter = new EventEmitter();
const timer = function (totalMs) {
setTimeout(() => {
eventEmitter.emit('tick');
tickCount++;
if (totalMs <= 0) {
return cb(tickCount);
}
timer(totalMs - 50);
}, 50);
};
timer(number);
return eventEmitter;
}
ticker(300, (tickCount) => console.log(`Tick count: `, tickCount)).on('tick', () => console.log('A tick is passed'));
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment