web woker以及使用场景
分享一个web woker 的案例

代码示例: worker: `
function getArrayLayer(arr, attr, index = 1) {
let newIndex = index;
for (const iterator of arr) {
let tempIndex = index
if (iterator[attr]) {
tempIndex = getArrayLayer(iterator[attr], attr, index + 1)
if (tempIndex > newIndex) {
newIndex = tempIndex
}
}
}
return newIndex
}
function calc(arr) {
const result = getArrayLayer(arr,'child')
self.postMessage(result)
}
self.onmessage = function (e) {
calc(e.data)
}
` html:
<!--
* @Author: moreal ncy970101@163.com
* @Date: 2023-10-30 13:45:32
* @LastEditors: moreal ncy970101@163.com
* @LastEditTime: 2023-12-21 15:32:36
* @FilePath: /web-worker/html/index.html
* @Description: 这是默认设置,请设置`customMade`, 打开koroFileHeader查看配置 进行设置: https://github.com/OBKoro1/koro1FileHeader/wiki/%E9%85%8D%E7%BD%AE
-->
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>Document</title>
</head>
<body>
<div>计算从 1 到给定数值的总和</div>
<input type="text" placeholder="请输入数字" id="num" />
<button onclick="calc()">开始计算</button>
<span>计算结果为:<span id="result">-</span></span>
<div>在计算期间你可以填XX表单</div>
<input type="text" placeholder="请输入姓名" />
<input type="text" placeholder="请输入年龄" />
<!-- <script>
function calc() {
const num = parseInt(document.getElementById('num').value)
let result = 0
let startTime = performance.now()
// 计算求和(模拟复杂计算)
for (let i = 0; i <= num; i++) {
result += i
}
// 由于是同步计算,在没计算完成之前下面的代码都无法执行
const time = performance.now() - startTime
console.log('总计算花费时间:', time)
document.getElementById('result').innerHTML = result
}
</script> -->
<script>
const worker = new Worker('../js/index.js')
function calc(){
const num = parseInt(document.getElementById('num').value)
worker.postMessage(num)
}
worker.onmessage = function (e){
document.getElementById('result').innerHTML = e.data
}
</script>
</body>
</html>