stop clock if all stopped

This commit is contained in:
Jade (Rose) Rowland 2024-03-10 14:35:43 -04:00
parent 30a5176090
commit 112ca1875a
2 changed files with 17 additions and 9 deletions

View File

@ -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.

View File

@ -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() {