Last active
September 28, 2022 16:33
-
-
Save r2abreu/65f2482f3416b1c6ae79411c5d45bd3a to your computer and use it in GitHub Desktop.
04-playing-with-errors
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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