S
S
Senbonzakuraa2020-12-27 18:43:16
Node.js
Senbonzakuraa, 2020-12-27 18:43:16

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)
        }
    
}

Client code:
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
    })
})

I thought that this was possible due to the fact that every time a user connects, a new event listener is created, but I tried to set it instead of on - once, but the event still fires a random number of times. Tried clearing the listeners before creating a new one, but the result is the same. Why is this happening? chanels[name].emitter.on('end'),chanels[name].emitter.removeAllListeners(['end']);

Answer the question

In order to leave comments, you need to log in

1 answer(s)
R
Roman, 2020-12-27
@Senbonzakuraa

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 question

Ask a Question

731 491 924 answers to any question