Skip to content

Instantly share code, notes, and snippets.

@r2abreu
Last active September 28, 2022 16:24
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 r2abreu/18f063f5fe98a96759dd8c3d860af4f5 to your computer and use it in GitHub Desktop.
Save r2abreu/18f063f5fe98a96759dd8c3d860af4f5 to your computer and use it in GitHub Desktop.
03-a-simple-modification
import { EventEmitter } from "events";
(function (number, callback) {
const EMITTER = new EventEmitter;
const MILLISECONDS_INTERVAL = 50;
let ticks = 0;
let elapsedTimeInMilliseconds = 0;
let intervalID;
function start() {
process.nextTick(tick);
intervalID = setInterval(itirate, MILLISECONDS_INTERVAL)
}
function itirate() {
if (elapsedTimeInMilliseconds >= number) return stop();
elapsedTimeInMilliseconds += MILLISECONDS_INTERVAL;
tick();
}
function tick() {
EMITTER.emit('tick');
ticks++;
}
function stop() {
clearInterval(intervalID);
return callback(null, ticks)
}
start();
return EMITTER;
})(1000, (error, result) => {
if (error) {
console.error(error)
} else {
console.log(`Number of ticks: ${result}`)
}
}).on('tick', () => console.log('Tick'))
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment