// Server-side code const express = require('express'); const http = require('http'); const socketIO = require('socket.io'); const app = express(); const server = http.createServer(app); const io = socketIO(server); let interval; let tempo = 120; // Initial tempo (beats per minute) let startTime; // Start time of the metronome io.on('connection', (socket) => { console.log('A client connected'); socket.on('start', () => { console.log('Metronome started'); startTime = Date.now(); // Set the start time // Calculate the delay between each beat based on the tempo const delay = (60 / tempo) * 1000; // Send a beat event to all connected clients at the specified interval interval = setInterval(() => { const elapsedTime = Date.now() - startTime; io.emit('beat', elapsedTime); }, delay); }); socket.on('stop', () => { console.log('Metronome stopped'); clearInterval(interval); }); socket.on('tempo', (newTempo) => { console.log(`Tempo set to ${newTempo} BPM`); tempo = newTempo; // If the metronome is already running, restart it with the new tempo if (interval) { clearInterval(interval); const delay = (60 / tempo) * 1000; interval = setInterval(() => { const elapsedTime = Date.now() - startTime; io.emit('beat', elapsedTime); }, delay); } }); socket.on('disconnect', () => { console.log('A client disconnected'); clearInterval(interval); }); }); server.listen(3000, () => { console.log('Server is running on port 3000'); }); return io;