【问题标题】:Problem with a for loop with countdown in node.jsnode.js中倒计时的for循环问题
【发布时间】:2021-02-15 13:46:53
【问题描述】:

我有以下代码,我已经尝试了一切,但我找不到解决方案,希望有人能帮助我。

至此代码执行fRoll.roll,进入FOR循环并执行EventEmitter的倒计时,最后再次执行fRoll.roll,但是不考虑时间执行了For循环的setInterval,对应于EventEmitterstartTimer ()

我的问题是如何让循环的每次迭代之间等待EventEmittersetInterval,然后执行侦听器。


  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

发生在我身上的是每次执行倒计时事件的侦听器时执行10次。

【问题讨论】:

  • 我认为您的设计需要考虑一些因素。您似乎在循环内的事件处理程序中添加事件处理程序。理想情况下,事件处理程序应该存在于循环之外并在任何上下文之外处理事件(事件处理程序附加到的对象的上下文除外)。
  • 感谢你的贡献,你能用代码表达我是怎么做的吗,我什么都试过了,我不能很好地控制事件@Heretic Monkey
  • 我建议阅读一些关于如何在 Node.js 中设置和使用事件的教程。网上已经有很多了;一些搜索会发现很多。例如,一个简短的搜索发现How to use Node.js Event Emitter
  • 谢谢 我在发布之前一直在看几个帖子,但我还没有找到如何将它们放在循环中@Heretic Monkey

标签: javascript node.js loops dom-events puppeteer


【解决方案1】:

我已经重新编写了sleep function 的代码,因为我还没有找到一种方法来使用 EventEmitterstartTimer () 作为循环的每次迭代的条件。


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

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2012-02-11
    • 2016-08-08
    • 2015-05-31
    • 2016-11-06
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多