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?