Quantcast
Channel: Active questions tagged html - Stack Overflow
Viewing all articles
Browse latest Browse all 74102

Why does my Web Worker stops decreasing a timer after couple of seconds?

$
0
0

I've came across with an interesting event.

I'm trying to build a pomodoro timer that runs in the background with an alarm that fires when the timer finishes and starts.

I coded a WebWorker Script that runs that same timer.

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;
}
})

And added an event listener to the pomodoro script that updates the timer display

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);
    });

The interesting thing here:

If i remove the console.log the timer stops getting updated. If i set it all goes with the plan.

Why does this happen???

Is there a way that the timer doesn't stop after couple of seconds if it's running on background?


Viewing all articles
Browse latest Browse all 74102

Trending Articles



<script src="https://jsc.adskeeper.com/r/s/rssing.com.1596347.js" async> </script>