Browsers are designed to optimize user experience and battery life, and they restrict the activity of background tabs to conserve CPU and power.
2 ways to dodge background execution supression is
(example on ping/pong messages):
1st -
inline:
// Web Worker code defined as a string
const workerCode = `
// When the worker receives a message...
onmessage = function(e) {
// ...if that message is 'start'
if (e.data === 'start') {
// ...set an interval to send a heartbeat every minute
setInterval(() => {
// Fetch a heartbeat from the server
fetch('http://127.0.0.1:9000/heartbeat')
.then(response => {
// If the response isn't okay, throw an error
if (!response.ok) {
throw new Error('Network response was not ok');
}
return response.json();
})
.then(data => {
// Log the received heartbeat
console.log('Heartbeat received:', data);
})
.catch(error => {
// If there's an error, log it
console.error('Fetch error:', error.message);
});
}, 60000);
}
};
`;
// Create a new Blob object from the worker code
const blob = new Blob([workerCode], { type: 'application/javascript' });
// Create a new Web Worker from the blob URL
const worker = new Worker(URL.createObjectURL(blob));
// Post a 'start' message to the worker to begin the heartbeat
worker.postMessage('start');
2nd -
worker.js file:
// When the worker receives a message...
onmessage = function(e) {
// ...if that message is 'start'
if (e.data === 'start') {
// ...set an interval to send a heartbeat every minute
setInterval(() => {
// Fetch a heartbeat from the server
fetch('http://127.0.0.1:9000/heartbeat')
.then(response => {
// If the response isn't okay, throw an error
if (!response.ok) {
throw new Error('Network response was not ok');
}
return response.json();
})
.then(data => {
// Log the received heartbeat
console.log('Heartbeat received:', data);
})
.catch(error => {
// If there's an error, log it
console.error('Fetch error:', error.message);
});
}, 60000);
}
};
main section:
// Create a new Web Worker from the external worker file
const worker = new Worker('worker.js');
// Post a 'start' message to the worker to begin the heartbeat
worker.postMessage('start');
transition
, so not all divs transition at the same time, but actually 15ms after eachother, creating some rolling effect. When I go to another tab and come back after a while, all divs transition at the same time and thesetTimeOut
is completely ignored. It's not a big problem for my project, but it is a weird and unwanted addition. – Toga