【发布时间】:2021-02-15 13:46:53
【问题描述】:
我有以下代码,我已经尝试了一切,但我找不到解决方案,希望有人能帮助我。
至此代码执行fRoll.roll,进入FOR循环并执行EventEmitter的倒计时,最后再次执行fRoll.roll,但是不考虑时间执行了For循环的setInterval,对应于EventEmitter的startTimer ()。
我的问题是如何让循环的每次迭代之间等待EventEmitter 的setInterval,然后执行侦听器。
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