S
S
Senbonzakuraa2020-12-21 23:02:30
Node.js
Senbonzakuraa, 2020-12-21 23:02:30

Is it possible to use a pattern or what is the best way to solve the problem?

There is socket.io serveralso a classRandom

class Random {
    constructor(timer) {
        this.timer = timer
        this.status = 0
    }
    async setStatus() {
        const interval = setInterval(()=> {
            this.timer -= 1
            if(this.timer <= 0) {
                this.status = 1
            }
        }, 1000)
    }

}

Socket.io server 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()
})


Problem:

I want to execute a certain event on the socket server in the event that this.status = 1.I need to track the change this.statusand notify the socket part about it

Question:

How can this be implemented? I tried to do it through setIntervalthe socket side, requesting every second this.state,, but in my opinion this is an extremely bad decision. I came across the observer pattern, but is it possible to implement it in my case?

Answer the question

In order to leave comments, you need to log in

1 answer(s)
A
Alexey, 2020-12-21
@Azperin

Mb will help

function Timer(t, ch) {
  this.time = t;
  this.channel = ch;
  
  this.interval = setInterval(() => {
    if (--this.time < 1) {
      clearInterval(this.interval);
      // здесь можно делать ченить с сокетом, он же полюбому глобальный
      // либо сделать свои ивенты через эммитер
      socket.to(this.channel).emit('TIMEOUT - STATUS ZERO');
    };
  }, 1000);
  
  this.getTimeleft = () => this.time;
  
  socket.to(this.channel).emit(`TIMER STARTS, YOU HAVE - ${this.time} SECONDS TO DO SOMETHING`);
};

var timer = new Timer(10, 'chanel2');
var timer2 = new Timer(3, 'chanel5');

Didn't find what you were looking for?

Ask your question

Ask a Question

731 491 924 answers to any question