浏览器旨在优化用户体验和电池寿命,它们限制后台标签的活动以节省CPU和电力。
避免后台执行抑制的两种方法是
(例如ping/pong消息的示例):
第一种方法 -
内联:
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);
}
};
`;
const blob = new Blob([workerCode], { type: 'application/javascript' });
const worker = new Worker(URL.createObjectURL(blob));
worker.postMessage('start');
第二 -
worker.js 文件:
onmessage = function(e) {
if (e.data === 'start') {
setInterval(() => {
fetch('http://127.0.0.1:9000/heartbeat')
.then(response => {
if (!response.ok) {
throw new Error('Network response was not ok');
}
return response.json();
})
.then(data => {
console.log('Heartbeat received:', data);
})
.catch(error => {
console.error('Fetch error:', error.message);
});
}, 60000);
}
};
主要部分:
// 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');