javascript - 为什么我的 Web Worker 在几秒钟后停止减少计时器?
问题描述
我遇到了一个有趣的事件。
我正在尝试构建一个在后台运行的番茄计时器,并在计时器完成和启动时触发警报。
我编写了一个运行相同计时器的 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;
}
})
并在番茄脚本中添加了一个事件监听器,用于更新计时器显示
番茄钟
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,计时器将停止更新。如果我设置这一切都符合计划。
为什么会这样???
如果计时器在后台运行,有没有办法让计时器在几秒钟后不会停止?
解决方案
推荐阅读
- visual-studio-code - 重新加载 keybindings.json 而不重新启动 vscode
- google-chrome - ubuntu:根据使用的配置文件对 chrome 窗口进行分组
- android - 如果片段中已经打开了一个新的警报对话框,如何避免打开一个新的警报对话框
- python - 通过格式不正确的 JSON 文件 python 解析
- python - 从 Python 将日期字符串插入 SQLite 会产生意外结果
- python - NoSuchModuleError:无法加载插件:sqlalchemy.dialects:teradata
- ios - iOS图表框架maximumFractionDigits不起作用
- r - 从多个线性模型中获取斜率、截距和确定系数,所有这些都来自同一个数据帧
- javascript - Javascript 按钮按条件显示
- visual-studio-code - vscode 在 Windows 7 上没有为我启动