首页 > 解决方案 > 为什么我的 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,计时器将停止更新。如果我设置这一切都符合计划。

为什么会这样???

如果计时器在后台运行,有没有办法让计时器在几秒钟后不会停止?

标签: javascripthtmlweb-worker

解决方案


推荐阅读