diff --git a/web-workers/animation-worker/README.md b/web-workers/animation-worker/README.md new file mode 100644 index 0000000..76705bd --- /dev/null +++ b/web-workers/animation-worker/README.md @@ -0,0 +1,13 @@ +# Worker Demo + +This demo demonstrates how to use a `Worker` to run long-running tasks in a background thread, preventing the main thread from being blocked. + +## showcase + +[Open the home page](https://mdn.github.io/dom-examples/web-workers/index.html) + +## description + +1. Open the home page. +2. Click the `start` button to view the animation effect. +3. Wait for the animation effect to finish before switching to the `optimize` button and clicking the `block` button. Observe the difference between using a Worker and not using a Worker, such as the transition from the `doing` state to the `done` state and the animation effect. \ No newline at end of file diff --git a/web-workers/animation-worker/animation.js b/web-workers/animation-worker/animation.js new file mode 100644 index 0000000..4ee311c --- /dev/null +++ b/web-workers/animation-worker/animation.js @@ -0,0 +1,64 @@ +const start = document.querySelector("#start"); +const stop = document.querySelector("#stop"); +const block = document.querySelector("#block"); +const performance = document.querySelector("#performance"); +const state = document.querySelector("#state"); + +let optimize = false; +let time = 0; +let animationId, + worker, + length = 2200; + +if (window.Worker) { + worker = new Worker("worker.js"); + worker.onmessage = function (e) { + state.textContent = e.data; + }; +} + +const animate = function () { + time++; + box.style.transform = `translateX(${time}px)`; + if (time < 600) { + animationId = requestAnimationFrame(animate); + } +}; + +const newElement = function () { + const span = document.createElement("span"); + span.style.display = "inline-block"; + span.style.width = "10px"; + span.style.height = "10px"; + span.style.backgroundColor = "red"; + span.style.margin = "2px"; + return span; +}; + +start.onclick = function () { + animationId = requestAnimationFrame(animate); +}; + +stop.onclick = function () { + cancelAnimationFrame(animationId); +}; + +block.onclick = function () { + state.textContent = "doing"; + if (optimize && worker) { + worker.postMessage({ length }); + } else { + for (let i = 0; i < length; i++) { + for (let j = i + 1; j < length; j++) { + for (let k = j + 1; k < length; k++) {} + } + } + state.textContent = "done"; + } +}; + +performance.onclick = function () { + optimize = !optimize; + if (optimize) performance.textContent = "Un-Optimize"; + else performance.textContent = "Optimize"; +}; diff --git a/web-workers/animation-worker/index.html b/web-workers/animation-worker/index.html new file mode 100644 index 0000000..d6da4d2 --- /dev/null +++ b/web-workers/animation-worker/index.html @@ -0,0 +1,38 @@ + + +
+ + +Result:
+ +Result:
+ +
All comments:
+