web-worker 独立线程,避免主线程阻塞
ref: https://github.com/zjy4fun/web-worker
分别使用主线程和 worker 线程处理一个耗时计算,看看对主线程上的 UI 渲染有什么影响
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8" />
<meta name="viewport" content="width=device-width, initial-scale=1.0" />
<title>Web Worker</title>
</head>
<body>
<script>
function task() {
let sum = 0;
for (let i = 0; i < 1e9; i++) {
sum += i;
}
return sum;
}
function mainThread() {
console.time("主线程计算耗时");
task();
console.timeEnd("主线程计算耗时");
}
mainThread();
</script>
<h1>Main Thread</h1>
</body>
</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</title>
</head>
<body>
<script>
function workerThread() {
console.time("Web Worker计算耗时");
const worker = new Worker("worker.js");
worker.postMessage("Hello, Web Worker!");
worker.onmessage = function (event) {
console.timeEnd("Web Worker计算耗时");
console.log("Received message from worker:", event.data);
}
}
workerThread();
</script>
<h1>Web Worker Thread</h1>
</body>
</html>
self.onmessage = function (event) {
function task() {
let sum = 0;
for (let i = 0; i < 1e9; i++) {
sum += i;
}
return sum;
}
const result = task();
self.postMessage(result);
};
对比效果
可以看出使用 web worker 可以避免让主线程阻塞