// Create a new web worker
const worker = new Worker('worker.js');
// Add an event listener to receive messages from the worker
worker.addEventListener('message', (event) => {
const { games } = event.data;
console.log('Received updated games from worker:', games);
});
// Function to send a message to the worker to update the games
function updateGames() {
worker.postMessage('updateGames');
}
// Set a timer to periodically update the games
setInterval(updateGames, REFRESH_TIME);
型
worker.js
// Initialize the games array
const games = [];
// Function to update the games
function updateGames() {
for (const game of games) {
game.update();
}
// Send the updated games back to the main script
self.postMessage({ games });
}
// Event listener to receive messages from the main script
self.addEventListener('message', (event) => {
const message = event.data;
if (message === 'updateGames') {
updateGames();
}
});
1条答案
按热度按时间ffx8fchx1#
这样,所有的代码都将在主线程中运行,所以如果你用true创建一个while循环,它将完全阻塞主线程。简单的方法是每秒调用更新函数X次。实现这一点的一种方法是:
字符串
这种方法应该可以工作,但请注意,它不能很好地扩展多个游戏,因为如果处理时间超过了一帧的分配时间,它将锁定整个应用程序。
解决这个问题的另一种方法是使用Web Workers。您可以使用一个工人池,甚至每个游戏一个工人。
对所有游戏使用一个Web Worker,您可以执行以下操作:
main.js
型
worker.js
型
一个更好的方法是使用一个工人池,其中每个工人更新一个游戏。