subWorker.js
self.onmessage = function (e) {
const { timer, ...row } = e.data
setTimeout(() => self.postMessage(row), timer)
}
Thread.js
export default (function () {
function main(options = {}) {
Object.assign(this, {
thread: 4, // 开启4个线程
part: 100, // 每段100个数据
delay: 15, // 延迟15ms抛出
...options,
})
}
const threads = [] // 存放线程对象
main.prototype.init = function ({ ok, end, data }) {
for (let i = 0; i < this.thread; i++) {
const w = new Worker('./subWorker.js')
w.onmessage = (e) => this.response(e, i, ok, end)
threads.push(w)
}
return this.send(data)
}
main.prototype.response = function (e, which, onOk, onEnd) {
const { isEnd, ...row } = e.data
onOk.call(this, { thread: which, ...row, code: '000000' })
if (isEnd) {
threads.forEach(u => u.terminate())
threads.length = 0
onEnd && setTimeout(onEnd, 0)
}
}
main.prototype.send = function (array = []) {
const portion = this.part
const sendNumber = Math.ceil(array.length / portion)
for (let i = 0; i < sendNumber; i++) {
let index = i % this.thread
threads[index].postMessage({
data: array.slice(portion * i, portion * (i + 1)),
isEnd: !(sendNumber - i - 1),
timer: i * this.delay,
})
}
return this
}
return main
})()
使用文件
import W from 'Thread.js'
var dom = document.querySelector('#app')
const BB = new W()
BB.init({
ok(res) {
// console.log('111', res, this)
res.data.forEach(u => {
var elem = document.createElement('div')
elem.className = "li"
elem.innerHTML = u
dom.appendChild(elem)
})
},
end() {
// 可以再次执行n次
BB.init({
ok(res) {
res.data.forEach(u => {
var elem = document.createElement('div')
elem.className = "li"
elem.innerHTML = u
dom.appendChild(elem)
})
},
}).send(Array(317).fill(1).map((u, x) => (x + 1)))
},
data: Array(5317).fill(1).map((u, x) => (x + 1))
})