// timer.worker.js
let timer = null;
let interval = 1000;

self.addEventListener('message', (e) => {  
  switch (e.data.command) {
    case 'start':
      startTimer(e.data.interval);
      break;
    case 'stop':
      stopTimer();
      break;
    case 'update':
      interval = e.data.interval;
      break;
  }
});

// 关闭时的清理逻辑
self.addEventListener('close', () => {
    stopTimer();
  });

function startTimer(newInterval) {
  interval = newInterval || interval;
  stopTimer(); // 先停止已有定时器
  self.postMessage({ type: 'tick', timestamp:performance.now() });
  timer = setInterval(() => {
    const timestamp = performance.now();
    self.postMessage({ type: 'tick', timestamp });
  }, interval);
}

function stopTimer() {
  if (timer) {
    clearInterval(timer);
    timer = null;
  }
}