From 112ca1875a8f2d65fa5168bc70f5c21e29a64bee Mon Sep 17 00:00:00 2001 From: "Jade (Rose) Rowland" Date: Sun, 10 Mar 2024 14:35:43 -0400 Subject: [PATCH] stop clock if all stopped --- packages/core/clockworker.js | 23 +++++++++++++++-------- packages/core/neocyclist.mjs | 3 ++- 2 files changed, 17 insertions(+), 9 deletions(-) diff --git a/packages/core/clockworker.js b/packages/core/clockworker.js index e16da478..c5442422 100644 --- a/packages/core/clockworker.js +++ b/packages/core/clockworker.js @@ -10,10 +10,11 @@ function getTime() { return Math.round(seconds * precision) / precision; } -let numPorts = 0; let num_cycles_at_cps_change = 0; let num_ticks_since_cps_change = 0; let cps = 0.5; +// {id: {started: boolean}} +const clients = new Map(); const duration = 0.1; const channel = new BroadcastChannel('strudeltick'); @@ -37,18 +38,23 @@ const sendTick = (phase, duration, tick, time) => { const clock = this.createClock(getTime, sendTick, duration); let started = false; -const startClock = () => { +const startClock = (id) => { + clients.set(id, { started: true }); if (started) { return; } clock.start(); started = true; }; -const stopClock = async () => { - //dont stop the clock if mutliple instances are using it... - if (!started || numPorts !== 1) { +const stopClock = async (id) => { + clients.set(id, { started: false }); + + const otherClientStarted = Array.from(clients.values()).some((c) => c.started); + //dont stop the clock if other instances are running... + if (!started || otherClientStarted) { return; } + clock.stop(); setCycle(0); started = false; @@ -77,9 +83,9 @@ const processMessage = (message) => { } case 'toggle': { if (payload.started) { - startClock(); + startClock(message.id); } else { - stopClock(); + stopClock(message.id); } break; } @@ -89,8 +95,9 @@ const processMessage = (message) => { this.onconnect = function (e) { // the incoming port const port = e.ports[0]; - numPorts = numPorts + 1; + port.addEventListener('message', function (e) { + console.log(e.data); processMessage(e.data); }); port.start(); // Required when using addEventListener. Otherwise called implicitly by onmessage setter. diff --git a/packages/core/neocyclist.mjs b/packages/core/neocyclist.mjs index 3cfb8d64..1ffb6fda 100644 --- a/packages/core/neocyclist.mjs +++ b/packages/core/neocyclist.mjs @@ -17,6 +17,7 @@ export class NeoCyclist { this.onToggle = onToggle; this.latency = 0.1; // fixed trigger time offset this.cycle = 0; + this.id = Math.round(Date.now() * Math.random()); this.worker = new SharedWorker(new URL('./clockworker.js', import.meta.url)); this.worker.port.start(); @@ -107,7 +108,7 @@ export class NeoCyclist { }; } sendMessage(type, payload) { - this.worker.port.postMessage({ type, payload }); + this.worker.port.postMessage({ type, payload, id: this.id }); } now() {