Worker.js创建多线程优化

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))
})
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值