Skip to content

Instantly share code, notes, and snippets.

@r2abreu
Last active September 28, 2022 16:33
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/65f2482f3416b1c6ae79411c5d45bd3a to your computer and use it in GitHub Desktop.
Save r2abreu/65f2482f3416b1c6ae79411c5d45bd3a to your computer and use it in GitHub Desktop.
04-playing-with-errors
import { EventEmitter } from "events";
(function (number, callback) {
const EMITTER = new EventEmitter;
const MILLISECONDS_INTERVAL = 50;
const TIMESTAMP_ERROR = new Error('Timestamp is divisile by 5');
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;
Date.now() % 5 ? tick() : propagateError();
}
function tick() {
EMITTER.emit('tick');
ticks++;
}
function stop() {
clearInterval(intervalID);
return callback(null, ticks)
}
function propagateError() {
callback(TIMESTAMP_ERROR);
EMITTER.emit('error', TIMESTAMP_ERROR);
}
start();
return EMITTER;
})(1000, (error, result) => {
if (error) {
console.error('[Callback:]', error)
} else {
console.log(`Number of ticks: ${result}`)
}
})
.on('error', (error) => console.error('[Emitter:]', error))
.on('tick', () => console.log('Tick'))
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment