Created
February 28, 2017 16:49
-
-
Save pbadenski/a4ce272dfdcb517974c3d01682395443 to your computer and use it in GitHub Desktop.
Priority based task execution in JS using WebWorker
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
const FastPriorityQueue = require("fastpriorityqueue"); | |
const setZeroTimeout = (callback: any) => { | |
const channel = new MessageChannel(); | |
channel.port1.onmessage = callback; | |
channel.port2.postMessage(""); | |
}; | |
const queue: any = new FastPriorityQueue( (a: any, b: any) => | |
a.data.priority > b.data.priority | |
); | |
self.addEventListener("message", (message: any) => { | |
queue.add(message); | |
if (isProcessing) { | |
return; | |
} | |
exec(); | |
}, false); | |
let isProcessing = false; | |
const exec = () => { | |
if (queue.isEmpty()) { | |
isProcessing = false; | |
return; | |
} | |
isProcessing = true; | |
processMessage(queue.poll()); | |
setZeroTimeout( () => { | |
exec(); | |
}); | |
}; | |
const processMessage = (message: any) => { | |
// do some more CPU intensive processing | |
(self as any).postMessage(...); | |
}; |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment