0

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

enter image description here

What happens to me is that it is executed 10 times for each time the listener of the countdown event is executed.

Brian Tompsett - 汤莱恩
  • 5,753
  • 72
  • 57
  • 129
  • Does this answer your question? [How can I wait In Node.js (JavaScript)? l need to pause for a period of time](https://stackoverflow.com/questions/14249506/how-can-i-wait-in-node-js-javascript-l-need-to-pause-for-a-period-of-time) – Nir Alfasi Feb 15 '21 at 13:50
  • I think your design needs some consideration. You appear to be adding event handlers within an event handler, inside of a loop. Ideally, event handlers should exist outside of loops and handle the event outside of any context (except the context of the object the event handler is attached to). – Heretic Monkey Feb 15 '21 at 13:56
  • Thanks for the contribution, could you express with code how I had to do it, I have tried everything and I do not control the events very well @Heretic Monkey – Robert Armand Feb 15 '21 at 14:04
  • I would suggest working through some tutorials on how to set up and use events in Node.js. There are many already on the internet; some searching will find plenty. For instance, a brief search found [How to use Node.js Event Emitter](https://medium.com/javascript-in-plain-english/how-we-can-use-node-js-event-emitter-5c9e39c38749) – Heretic Monkey Feb 15 '21 at 14:08
  • Thanks I have been looking at several posts before publishing, but I have not found how to put them in a loop @Heretic Monkey – Robert Armand Feb 15 '21 at 14:11
  • @Nir Alfasi I need to be able to put the condition of the countdown of the event in the loop, so that every time I iterate it respects the startTimer (), if possible, I am very green with the events. – Robert Armand Feb 15 '21 at 14:19
  • @RobertArmand I think you should focus the question on the "wanted behavior". Right now you're focusing on your solution to the problem and its issues, but I'm not sure it's clear what is the desired behavior, or, *what* are you trying to achieve (notice: "what" not "how"). – Nir Alfasi Feb 15 '21 at 14:25
  • what I am trying to achieve, is that every time the loop is executed, I wait 1 hour to perform the listeners actions, but my question is if it can be put as a condition of the loop to; startTimer () { const timer = setInterval (() => { this.currentTime ++; this.emit ('update', this.currentTime); of the EventEmitter. @Nir Alfasi – Robert Armand Feb 15 '21 at 14:29
  • @RobertArmand again, this is a description of the solution - not a description of how the system should behave from the user perspective! This kind of description should *not* need to involve code at all! – Nir Alfasi Feb 15 '21 at 14:30
  • @Nir Alfasi I cannot advance in this code, I have been stuck at this point and cannot find a solution to my problem – Robert Armand Feb 15 '21 at 14:38
  • And unless you'll explain what is it that you're trying to achieve it will be very difficult to help you... – Nir Alfasi Feb 15 '21 at 15:07
  • Thanks for staying there, look, the only thing I need is to repeat the loop X number of times, but that each time the loop is executed, wait 1 hour and execute the code of the EventEmitter listeners, it is possible to put it as a condition of the loop counts down the event, so that it executes the listeners within each iteration of the loop ?? @Nir Alfasi – Robert Armand Feb 15 '21 at 15:11
  • The user who runs this program doesn't know what a loop is and what EventEmitter and listeners are. Defining what the program should do from the **user's** point of view is the key here. You keep going back to explaining what you're code is trying to do instead of explaining what is it that we're trying to achieve. If you'll be able to give this kind of description you may be surprised to see answers that do not use event-listener, loops or anything else like what you implemented. – Nir Alfasi Feb 16 '21 at 09:47
  • I also recommend reading about the [XY problem](https://xyproblem.info/) which is what we're having here. – Nir Alfasi Feb 16 '21 at 09:47
  • Example for such a description: the user can define a number, and a counter that starts from this number will be created, every second the counter will increase by one and its number should be displayed. – Nir Alfasi Feb 16 '21 at 09:49
  • @Nir Alfasi Thanks for the contributions, I understood you from the first moment, only that I tried to do it with events, since I have not found a way to do it, I answer my question with a correction of my code. – Robert Armand Feb 16 '21 at 12:55

1 Answers1

0

I have redone the code for a sleep function, as I have not found a way to use thestartTimer ()of the EventEmitter as a condition for each iteration of the loop.


const appGlobal = async (page, website) => {

try {

async function sleep(sec) {
  return new Promise((resolve) => {
    setTimeout(function () {
      resolve()
    }, sec * 1000)
  })
}

async function roll() {
  let count = 10000
  for (let start = 1; start < count; start++) {

    // We call the roll
    const freeRoll = require('../task/roll')(page, website)
    freeRoll.roll

    let random = Math.round(Math.random() * 8)
    console.log("Number is:" + " " + random)

    if (random === 3) {

      // We call the wine
      const fwine = require('../task/wine')(page, website)
      fwine.wine

      await sleep(3600)
    } else {
      await sleep(3600)
    }
  }

}

roll();

} catch (e) {
console.log('Error intro app-global:', e)

 }

}

module.exports = appGlobal