我遇到了一个有趣的事件。
我正在尝试构建一个Pomodoro计时器,该计时器在后台运行,并在计时器结束并启动时发出警报。
我编写了一个运行同一计时器的WebWorker脚本。
worker.js
self.addEventListener("message", (e) => {
if (e.data.task === 'run the timer') {
currentTimeLeftInSession = e.data.defaultWorkTime;
countdown = setInterval(() => {
currentTimeLeftInSession--;
currentTimeLeftInSessionBackwards++;
if(currentTimeLeftInSession < 0) {
return;
}
let timeLeft = getTimeLeft(currentTimeLeftInSession);
let data = {
'timeLeft': timeLeft,
}
self.postMessage(data);
}, 1000);
}
function getTimeLeft(seconds) {
let minutes = Math.floor(seconds / 60);
let remainderSeconds = Math.floor(seconds % 60);
let timeLeft = `${minutes}:${remainderSeconds}`;
if (remainderSeconds < 10) {
timeLeft = `${minutes}:0${remainderSeconds}`;
if (minutes < 10) {
timeLeft = `0${minutes}:0${remainderSeconds}`;
}
}
return timeLeft;
}
})
并在pomodoro脚本中添加了一个事件监听器,以更新计时器显示
pomodoro.js
let worker = new Worker('/lib/js/worker.js')
worker.addEventListener('message', (e) => {
progressBar.text.innerText = e.data.timeLeft;
console.log(e.data.timeLeft)
if(e.data.timeLeft == '00:00') {
playAudio(audioNumber);
}
});
startButton.addEventListener('click', () => {
defaultWorkTime = 200
let data = {
'task': 'run the timer',
'defaultWorkTime': defaultWorkTime,
'defaultBreakTime': defaultBreakTime,
}
worker.postMessage(data);
});
如果我删除了 console.log ,计时器将停止更新。如果我设置了,一切都会按计划进行。
为什么会这样?