This doesn't help - How can I make setInterval also work when a tab is inactive in Chrome? Actually, my code below is pretty similar...
The purpose: I need to take 25 minutes (15.000 seconds) and make a countdown to 0.
The problem: It doesn't work in inactive tabs on Mac. It slows down or even stops fully after some period of time.
I tried different options:
Moved the logic to a Worker (a separate worker.js file)
Used the difference between started Date and the current Date in the function
Used this lib https://github.com/turuslan/HackTimer
And lots of different own variants of the code
Nothing helped...
My worker.js:
let timerId;
self.onmessage = function(evt) {
if (evt.data.command === 'start' || evt.data.command === 'stop') {
clearInterval(timerId);
}
if (evt.data.command === "start") {
let seconds = evt.data.value;
timerId = setInterval(function() {
seconds--;
let currentSeconds = parseInt(Date.now() / 1000, 10);
let secondsLeft = evt.data.finishedAt - currentSeconds;
console.log(secondsLeft, seconds);
if (secondsLeft !== seconds) {
seconds = secondsLeft;
}
self.postMessage(seconds);
}, 1000);
}
};
But this tricky logic doesn't help:
if (secondsLeft !== seconds) {
seconds = secondsLeft;
}
How I use my worker:
let startedAt = parseInt(Date.now() / 1000, 10);
let finishedAt = startedAt + v.currentState.timer.value;
v.currentState.worker.postMessage({
'command': 'start',
'value': v.currentState.timer.value,
'startedAt': startedAt,
'finishedAt': finishedAt
});
v.currentState.worker.onmessage = function(e) {
v.currentState.timer.value = e.data;
};