worker.js 2.3 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132
  1. const {fib} = require('../../../../util/util.js')
  2. Page({
  3. onShareAppMessage() {
  4. return {
  5. title: '多线程Worker',
  6. path: 'page/API/pages/worker/worker'
  7. }
  8. },
  9. data: {
  10. res: '',
  11. input: 35,
  12. },
  13. onLoad() {
  14. this._worker = wx.createWorker('workers/fib/index.js')
  15. },
  16. onUnload() {
  17. clearInterval(this.interval)
  18. if (this._worker) this._worker.terminate()
  19. },
  20. bindInput(e) {
  21. const val = Number(e.detail.value)
  22. if (val > 40) return {value: 40}
  23. if (Number.isNaN(val)) return {value: 33}
  24. this.setData({
  25. input: val
  26. })
  27. return undefined
  28. },
  29. reset() {
  30. this.setData({res: ''})
  31. },
  32. compute() {
  33. this.reset()
  34. wx.showLoading({
  35. title: '计算中...'
  36. })
  37. const t0 = +Date.now()
  38. const res = fib(this.data.input)
  39. const t1 = +Date.now()
  40. wx.hideLoading()
  41. this.setData({
  42. res,
  43. time: t1 - t0
  44. })
  45. },
  46. multiThreadCompute() {
  47. this.reset()
  48. wx.showLoading({
  49. title: '计算中...'
  50. })
  51. const t0 = +Date.now()
  52. this._worker.postMessage({
  53. type: 'execFunc_fib',
  54. params: [this.data.input]
  55. })
  56. this._worker.onMessage((res) => {
  57. if (res.type === 'execFunc_fib') {
  58. wx.hideLoading()
  59. const t1 = +Date.now()
  60. this.setData({
  61. res: res.result,
  62. time: t1 - t0
  63. })
  64. }
  65. })
  66. },
  67. onReady() {
  68. this.position = {
  69. x: 150,
  70. y: 150,
  71. vx: 2,
  72. vy: 2
  73. }
  74. this.drawBall()
  75. this.interval = setInterval(this.drawBall, 17)
  76. },
  77. drawBall() {
  78. const p = this.position
  79. p.x += p.vx
  80. p.y += p.vy
  81. if (p.x >= 300) {
  82. p.vx = -2
  83. }
  84. if (p.x <= 7) {
  85. p.vx = 2
  86. }
  87. if (p.y >= 300) {
  88. p.vy = -2
  89. }
  90. if (p.y <= 7) {
  91. p.vy = 2
  92. }
  93. const context = wx.createContext()
  94. function ball(x, y) {
  95. context.beginPath(0)
  96. context.arc(x, y, 5, 0, Math.PI * 2)
  97. context.setFillStyle('#1aad19')
  98. context.setStrokeStyle('rgba(1,1,1,0)')
  99. context.fill()
  100. context.stroke()
  101. }
  102. ball(p.x, 150)
  103. ball(150, p.y)
  104. ball(300 - p.x, 150)
  105. ball(150, 300 - p.y)
  106. ball(p.x, p.y)
  107. ball(300 - p.x, 300 - p.y)
  108. ball(p.x, 300 - p.y)
  109. ball(300 - p.x, p.y)
  110. wx.drawCanvas({
  111. canvasId: 'canvas',
  112. actions: context.getActions()
  113. })
  114. },
  115. })