Empresas
Empregos
  • Sobre nós
  • Soluções
    • Publicação de vagas
      Publique sua vaga e receba candidatos qualificados em 48h.
    • Avaliações de candidatos
      Mais de 500 testes técnicos e psicológicos, mais anti-fraude.
    • Headhunting
      Busca executiva personalizada do início ao fim.
    • Folha de Pagamento + EOR
      Dispersão de folha e EOR em mais de 15 países da LATAM.
  • Preços
  • Empregos

0

186
Visualizações
socket bug in socket.io

I'm trying to use the socket.io library to create a simple game. The point of the game is to display same number to everyone connected to the website

var init = false
var init_pause = false
var send_message = false
var number = 0
var pause_start = 0
var paused = false

function rising_number() {
    if (!init) {
        paused = false
        number = 0
        init = true
        init_pause = false
    }
    if (number < 1000) {
        number = number + 1
    }
    else 
    {
        paused = true
        if (!init_pause) {
            pause_start = new Date().getTime()
            send_message = true
            init_pause = true
        }
        //this just waits until 2 seconds pass
        if ((new Date().getTime() - pause_start) / 1000 >= 2) {
            init = false
        }
    }
}

setInterval(rising_number, 5)

io.on("connection", socket => {
    function send_result() {
        if (!paused) {
            socket.emit('number', {number: number})
        }
        if (send_message) {
            socket.emit('number', {ended: true})
            console.log("round ended")
            send_message = false
        }
    }
    setInterval(() => send_result(), 50)
})

So the function rising_number is calculating the number that should be displayed to the users. When the number is equal to 1000, the game gets paused and the pause gets initialized so the variable send_message is now set to true. When the user is connected and send_message is true ended: true should be emitted. But I tried console logging the ended variable on the frontend and it gets recieved about 50% of the times, although "round ended" gets console logged every single time send_message is true. Why is this happening and is there a way to fix it?

about 4 years ago · Juan Pablo Isaza
Responde à pergunta
Encontrar trabalhos remotos

Descubra a nova forma de encontrar um emprego!

melhores empregos
Principais categorias de trabalho
Empresas
Postar vaga Preços Comercial
Jurídico
Termos e Condições Política de privacidade
© 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Recomende algumas ofertas para mim
Preciso de ajuda