I have the following code and I have tried everything, but I can't find the solution, I hope someone can help me.
So far the code executes the fRoll.roll
, enters the FOR
loop and executes the countdown of the EventEmitter
, at the end it executes the fRoll.roll
again, but the For loop is executed without respecting the time of the setInterval
, which corresponds to the startTimer ()
of the EventEmitter
.
My question is how can I make between each iteration of the loop wait for the setInterval
of the EventEmitter
and then execute the listeners.
const appGlobal = async (page, website) => {
const { EventEmitter } = require('events');
try {
class CountDownRoll extends EventEmitter {
constructor(CountDownRollTime) {
super();
this.CountDownRollTime = CountDownRollTime;
this.currentTime = 0;
}
startTimer() {
const timer = setInterval(() => {
this.currentTime++;
this.emit('update', this.currentTime);
// Check if CountDownRoll has reached to the end
if (this.currentTime === this.CountDownRollTime) {
clearInterval(timer);
this.emit('roll');
}
// Check if CountDownRoll will end in 10 minutes
if (this.currentTime === this.CountDownRollTime - 600) {
this.emit('end-soon');
}
}, 1000);
}
}
//======================================================
// this code is executed
const fRoll = require('../task/roll')(page, website)
fRoll.roll
//======================================================
// I need this loop to repeat itself X number of times and in each iteration,
// wait for the countdown before executing the codes.
const count = 10
for (let start = 1; start < count; start++)
const myCountDownRoll = new CountDownRoll(3600);
// Countdown
myCountDownRoll.on('update', (timer) => {
console.log(`${timer} seconds has been passed since the timer started`);
// code that performs at the end of the countdown
myCountDownRoll.on('roll', () => {
console.log('✓ CountDownRoll is completed');
//======================================================
// this code is executed
const fRoll = require('../task/roll')(page, website)
fRoll.roll
//======================================================
});
// Code that performs when reaching a specific time of the countdown
myCountDownRoll.on('end-soon', () => {
console.log('✓ Count down will be end in 600 seconds');
// Code to execute here
});
myCountDownRoll.startTimer();
}
} catch (e) {
console.log('Error intro app-global:', e)
}
}
module.exports = appGlobal
What happens to me is that it is executed 10 times for each time the listener of the countdown event is executed.