现在的web开发相对于几年前已经不可同日而语,不仅仅是简单的接口拿数据展示,而在有时候也会有大量的数据处理,尤其在接口返回数据不规范且数据量巨大的时候,仅仅在主线程处理就会有页面卡顿的现象,这时候就需要用到 worker 多线程,用子线程来处理复杂的逻辑运算,主线程只需要处理view层展示就好,bingo~~
// worker.js
class WebWorker {
constructor(worker: WebWorker) {
let code = worker.toString();
code = code.substring(code.indexOf('{') + 1, code.lastIndexOf('}'));
const blob = new Blob([code],{type: 'text/javascript'});
// worker地址为同源地址
return new Worker(URL.createObjectURL(blob));
}
}
export const workers = () => {
function workerCode(this: Worker){
this.onmessage = (e: MessageEvent) => {
for (let index = e.data.num; index < 10000; index++) {
this.postMessage(index)
}
this.postMessage(JSON.stringify(e))
}
this.postMessage(JSON.stringify({}))
}
const myWorker = new WebWorker(workerCode);
return myWorker;
}
// index.tsx
import { useEffect } from 'react'
import { workers } from '../../worker'
const Index:FC<any> = (props) => {
useEffect(() => {
const worker = workers() as Worker
worker.postMessage(JSON.stringify({ num: 0 }))
worker.onmessage = ({ data }) => {
const resData = JSON.parse(data)
console.log('====================================')
console.log(resData, 'message')
console.log('====================================')
}
return () => worker.terminate();
}, [])
}