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);
})
clearInterval
MUST be the value (id) returned bysetInterval
. It cannot be anything else. In your case you do not save the value returned bysetInterval
to a variable. You need to do that