Answer the question
In order to leave comments, you need to log in
Why does the event fire multiple times?
Main class:
class Random {
constructor(timer) {
this.timer = timer
this.status = 0
this.emitter = new EventEmitter()
}
async setStatus() {
const interval = setInterval(()=> {
this.timer -= 1
if(this.timer <= 0) {
this.status = 1
this.emitter.emit('end', this.status)
}
}, 1000)
}
}
const Random = require('../Random').Random
const chanels = {}
const timers = [{timer: 20, name: "chanel1"},{timer: 400, "chanel2"}]
timers.map((timer,id) => chanels[timer.name] = new Random(timer.time))
socket.on('startTimer', async (name, callback) => {
await chanels[name].setStatus()
chanels[name].emitter.on('end', (data)=> {
console.log(data) //Выводит несколько раз подряд содержимое Data
})
})
chanels[name].emitter.on('end'),
chanels[name].emitter.removeAllListeners(['end']);
Answer the question
In order to leave comments, you need to log in
you have 2 jambs in the code.
You understood the first one yourself, every time you connect, you launch a new "end" event listener, and even if the event occurs 1 time, and the listeners are set as once, each of the already launched, but never triggered listeners will still work.
The second problem is that you don't complete the running setInterval, which keeps decrementing the timer every second, even after the timer goes below zero. As a result, when the timer reaches zero, the if(this.timer <= 0) condition starts to work for every tick
Didn't find what you were looking for?
Ask your questionAsk a Question
731 491 924 answers to any question