I am using web worker (WW) for an animation. I use WW instead of using setInterval to avoid problem setInterval is stopped when tab is in active. But the WW seems to use so much CPU, it always take at least 37 - 38% of CPU. Can you please advise any solution how to reduce this usage? Live demo: https://repl.it/repls/SweetPowerlessKeychanger#worker.js
Below is my code. Thank you so much.
- Index.html:
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>Web Worker 1</title>
<style>
#it {
width: 50px;
height: 50px;
background: red;
border-radius: 50%;
position: fixed;
top: 50px;
}
</style>
</head>
<body>
<div id="it"></div>
<script src="main.js"></script>
</body>
</html>
- Main.js (Mother of the worker):
const it = document.getElementById("it");
it.style.left = "10px";
const maxLeft = window.innerWidth - 50;
const worker = new Worker("./worker.js");
worker.postMessage({
currentX: 10,
limit: maxLeft
});
worker.onmessage = (ev) => {
const data = ev.data;
it.style.left = data + "px";
worker.postMessage({
currentX: parseFloat(it.style.left),
limit: maxLeft
})
};
- worker.js:
let speed = 0.05;
onmessage = (ev) => {
const {currentX, limit} = ev.data;
if (currentX >= limit) {
speed = -0.05
}
if (currentX <= 0) {
speed = 0.05
}
postMessage(currentX + speed)
}