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

287
Visualizações
clearinterval not stopping setInterval function getting called - nodejs with socket io

on the client side i just set up two buttons, one to call socket.on('start-white-clock') and another to call socket.on('start-black-clock')

it's for a chess game

my aim is to stop the white timer when the black timer starts vice versa

with the code below when i call socket.on('start-black-clock') which calls the function blackClock() the function starts and begins to count down - logging blackClockTime: 18000, 17990, 17980 ..... etc etc

though when i then call socket.on('start-white-clock') which calls clearInterval(blackClock);

its doesn't stop blackClock() logging blackClockTime: 18000, 17990, 17980 ..... etc etc it just keeps going as if nothing has happened?

//server.js

const express = require('express'); //Line 1
const app = express(); //Line 2

const http = require('http').Server(app);

const io = require('socket.io')(5000)


var time = 180000





//Whenever someone connects this gets executed
io.on('connection', socket => {

    console.log('A user connected - this is socket.id: ' + socket.id);

    //Whenever someone disconnects this piece of code executed
    socket.on('disconnect', function () {
       console.log('Socket disconnected: ' + socket.id)
    });

    socket.on("join-game", (usersEmail, gameId, pageCalledFrom) => {
        socket.join(gameId)
theGameId = gameId
    })







var blackClockOn = false
  var blackClockTime = 18000
 
function blackClock() {
     blackClockTime = blackClockTime - 10
     console.log("blackClockTime: " + blackClockTime)
}


var theGameId;
var whiteClockTime = 18000
var whiteClockOn = false
function whiteClock() {
    whiteClockTime = whiteClockTime - 10
    console.log("white clock time: " + whiteClockTime)
  
}




//start white 
socket.on('start-white-clock',(usersEmail,currentGameId) => {
    console.log("start white clock called")
    whiteClock() 
     setInterval(whiteClock, 1000);
    clearInterval(blackClock); 

})


    //start black 
    socket.on('start-black-clock',(usersEmail,currentGameId) => {
        console.log("start black clock called")
        blackClock()
        setInterval(blackClock, 1000);
       clearInterval(whiteClock); 
    })

about 4 years ago · Juan Pablo Isaza
2 Respostas
Responde à pergunta

0

This is because clearInterval() receives an integer as an argument. this integer is the id of the interval, which is returned by the function setInterval().
so you would need to define 2 variables outside of the socket.on() callbacks:
let blackInterval, whiteInterval;
then

socket.on('start-white-clock',(usersEmail,currentGameId) => {
console.log("start white clock called")
whiteClock() 
whiteInterval = setInterval(whiteClock, 1000);
if(blackInterval) clearInterval(blackInterval);
})

and

  socket.on('start-black-clock',(usersEmail,currentGameId) => {
    console.log("start black clock called")
    blackClock()
    blackInterval = setInterval(blackClock, 1000);
// conditional not needed here as white always starts so its interval should be defined
   clearInterval(whiteInterval); 
})
about 4 years ago · Juan Pablo Isaza Relatório

0

Try this.

const intervalID = setInterval(.....);
clearInterval(intervalID);
about 4 years ago · Juan Pablo Isaza Relatório
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