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);
})
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);
})
Try this.
const intervalID = setInterval(.....);
clearInterval(intervalID);