Skip to content

Instantly share code, notes, and snippets.

@madeinfree
Last active December 19, 2020 09:29
Show Gist options
  • Save madeinfree/581e4fd2bfee2d840c85e2f54f55ce88 to your computer and use it in GitHub Desktop.
Save madeinfree/581e4fd2bfee2d840c85e2f54f55ce88 to your computer and use it in GitHub Desktop.
透過 Web Workers API 改善 React 大量計算阻塞渲染幀數01.medium
import React, { useState, useEffect } from "react";
import "./styles.css";
export default function App() {
const [sum, setSum] = useState(0);
useEffect(() => {
const worker = new Worker("./computing.js");
worker.addEventListener("message", (e) => {
const data = e.data;
setSum(data);
});
worker.postMessage([0, 1000000000]);
}, []);
return (
<div className="App">
<h1>Hello CodeSandbox</h1>
<h2>Count Sum: {sum}</h2>
</div>
);
}
onmessage = (e) => {
const [num1, num2] = e.data;
let sum = 0;
for (let i = num1; i < num2; i++) {
sum += i;
}
postMessage(sum);
};
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment