feat(timer): move timer to Web Worker and add title anchor

This commit is contained in:
djg 2026-09-23 17:05:45 +00:00
parent 9b8f00a985
commit 7563929975
2 changed files with 71 additions and 4 deletions

View file

@ -290,9 +290,24 @@
var timerState = store('timer_state');
var timer;
if (timerState && timerState.left > 0) {
timer = { total: timerState.total, left: timerState.left, running: false, phase: timerState.phase || 'focus', iv: null };
timer = { total: timerState.total, left: timerState.left, running: false, phase: timerState.phase || 'focus' };
} else {
timer = { total: 25 * 60, left: 25 * 60, running: false, phase: 'focus', iv: null };
timer = { total: 25 * 60, left: 25 * 60, running: false, phase: 'focus' };
}
var timerWorker = null;
if (window.Worker) {
timerWorker = new Worker('/static/timer-worker.js');
timerWorker.onmessage = function (e) {
if (e.data.tick) {
timer.left = e.data.left;
timerPersist();
timerPaint();
} else if (e.data.complete) {
timerComplete();
timerPaint();
}
};
}
function timerPersist() {
@ -315,6 +330,7 @@
function timerPaint() {
var m = Math.floor(timer.left / 60), s = timer.left % 60;
$('#timer-time').textContent = (m < 10 ? '0' : '') + m + ':' + (s < 10 ? '0' : '') + s;
updateTimerTitle();
$('#ring-fg').style.strokeDashoffset = CIRC * (1 - timer.left / timer.total);
var portion = timer.total > 0 ? (timer.left / timer.total) : 0;
@ -355,8 +371,35 @@
}
}
function timerStop() { clearInterval(timer.iv); timer.iv = null; timer.running = false;
timerPersist(); }
function timerStop() {
if (timerWorker) timerWorker.postMessage({ command: 'stop' });
timer.running = false;
timerPersist();
resetTitle();
}
const originalTitle = document.title;
function resetTitle() {
document.title = originalTitle;
}
function updateTimerTitle() {
if (!timer.running) {
resetTitle();
return;
}
const m = Math.floor(timer.left / 60);
const s = timer.left % 60;
const timeStr = (m < 10 ? '0' : '') + m + ':' + (s < 10 ? '0' : '') + s;
const phaseLabel = timer.phase === 'focus' ? 'Focus' : 'Break';
const ctxText = $('#timer-context-text').textContent;
if (ctxText && ctxText.trim() !== '') {
document.title = `(${m}m) [${ctxText}] - myADHD`;
} else {
document.title = `(${timeStr}) ${phaseLabel} - myADHD`;
}
}
function timerComplete() {
timerStop(); beep();

View file

@ -0,0 +1,24 @@
let interval = null;
let secondsLeft = 0;
self.onmessage = function(e) {
const data = e.data;
if (data.command === 'start') {
secondsLeft = data.seconds;
if (interval) clearInterval(interval);
interval = setInterval(() => {
secondsLeft--;
self.postMessage({ tick: true, left: secondsLeft });
if (secondsLeft <= 0) {
clearInterval(interval);
interval = null;
self.postMessage({ complete: true });
}
}, 1000);
} else if (data.command === 'stop' || data.command === 'pause') {
if (interval) {
clearInterval(interval);
interval = null;
}
}
};