Last active
September 28, 2022 16:24
-
-
Save r2abreu/18f063f5fe98a96759dd8c3d860af4f5 to your computer and use it in GitHub Desktop.
03-a-simple-modification
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; | |
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