imba-web-worker
v1.0.1
Published
web worker 浏览器线程
Downloads
4
Readme
imba-web-worker
安装
# pnpm
pnpm i imba-web-worker
使用
import webWorker from 'imba-web-worker'
const worker = new ImbaWebWorker(new Worker('./worker.js'))
worker.timeout = 3000 // 默认9000
// 以下并发模式,串行模式自己代码task await
for (let i = 0; i < worker.maxThread; i++) {
worker.run(`index=${i}`).then((res) => {
console.log('%c [ res ]-11111111', 'font-size:14px; background:#41b883; color:#ffffff;', res)
})
}
worker.js
// 在 Web Worker 中执行的代码
// importScripts('./xxxx.js')
async function calculate(workId) {
const now = new Date().getTime()
console.time(`${workId}-总耗时`)
for (let i = 0; i < 2000; i++) {
const text = JSON.stringify({ a: 1, b: { c: 2, d: [3, 4, 5] } })
const json = JSON.parse(text)
}
console.timeEnd(`${workId}-总耗时`)
return new Date().getTime() - now
}
self.addEventListener('message', async (e) => {
const { workId, data } = e.data
const res = await calculate(workId)
self.postMessage({ workId, data: res })
})
测试示例
<!DOCTYPE html>
<html>
<head>
<title>test示例</title>
<style>
#loading {
font-size: 24px;
animation: animate-loading 1s infinite;
}
@keyframes animate-loading {
0% {
color: blue;
}
25% {
color: red;
}
50% {
color: green;
}
75% {
color: yellow;
}
100% {
color: orange;
}
}
</style>
</head>
<body>
<h1 id="button">test示例</h1>
<div id="loading">loading...</div>
<div id="random"></div>
<script>
setInterval(() => {
document.querySelector('#random').innerHTML = Math.random().toString(16)
}, 300)
</script>
<script type="module">
import { ImbaWebWorker } from '../dist/index.mjs.js'
document.querySelector('#button').addEventListener('click', () => {
const worker = new ImbaWebWorker(new Worker('./worker.js'))
const worker2 = new ImbaWebWorker(new Worker('./worker2.js'))
worker.timeout = 3000
worker2.timeout = 30000
const thread = worker.maxThread / 2
for (let i = 0; i < thread; i++) {
worker.run(`index=${i}`).then((res) => {
console.log('%c [ res ]-11111111', 'font-size:14px; background:#41b883; color:#ffffff;', res)
})
}
for (let i = 0; i < thread; i++) {
worker2.run(`index=${i}`).then((res) => {
console.log('%c [ res ]-22222222', 'font-size:14px; background:#41b883; color:#ffffff;', res)
})
}
})
</script>
</body>
</html>