Business
Jobs
  • About Us
  • Solutions
    • Job Postings
      Post your job and receive qualified candidates in 48h.
    • Candidate Assessments
      500+ technical and psychological tests, plus anti-fraud.
    • Headhunting
      Tailor-made executive search from start to finish.
    • Payroll + EOR
      Payroll dispersal and EOR across 15+ LATAM countries.
  • Pricing
  • Jobs

0

182
Views
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
Answer question
Find remote jobs

Discover the new way to find a job!

Top jobs
Top job categories
Business
Post vacancy Pricing Sales
Legal
Terms and conditions Privacy policy
© 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Show me some job opportunities
There's an error!