Skip to content

Instantly share code, notes, and snippets.

@whitehat101
Last active October 8, 2018 11:14
Show Gist options
  • Save whitehat101/2eb2cbc53247689f97ab77c2265aebf2 to your computer and use it in GitHub Desktop.
Save whitehat101/2eb2cbc53247689f97ab77c2265aebf2 to your computer and use it in GitHub Desktop.
Web Worker Queue for Uint32s
worker = new Worker 'queued_worker.js'
worker.onmessage = (msg) -> console.log 'Message received from worker', msg.data
worker.onerror = (error) -> console.log 'Error received from worker', error
# arr = new Uint32Array([1,2,3])
# worker.postMessage(arr, [arr.buffer])
# worker.postMessage({ticket: 123})
# worker.postMessage({ticket: 123, head: true})
# uint = new Uint32Array(0xffffff); // 67.1 MB
# uint.forEach((v,i)=>uint[i]=Math.floor(0xffffffff*Math.random()));
# worker.postMessage(uint,[uint.buffer])
## Queued Worker
# arr = new Uint32Array([1,2,3])
# worker.postMessage(arr, [arr.buffer])
# worker.postMessage({ticket: 123})
# worker.postMessage({ticket: 123, head: true})
##
import sleep from './sleep.coffee'
console.log 'queued_worker'
isRunning = false
queue = []
tick = ->
console.log "queue.length = #{queue.length}"
unless queue.length
isRunning = false
return
id = do queue.shift
console.log "#{id} start"
sleep 3000
self.postMessage "#{id} done"
setTimeout tick
self.onerror = (e) -> console.log 'self.onerror', e
self.onmessage = (e) ->
console.log 'Message received from main script', e.data
if e.data instanceof Uint32Array
for i in [0...e.data.length] by 0xEFFF
sub = e.data.subarray i, i + 0xEFFF
Array::push.apply queue, sub
else
if e.data.head
queue.unshift e.data.ticket
else
queue.push e.data.ticket
# remove duplicates
queue = [...new Set queue]
unless isRunning
isRunning = true
do tick
return
export default (miliseconds) ->
currentTime = new Date
while new Date - currentTime <= miliseconds
undefined
return
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment