Skip to content

Instantly share code, notes, and snippets.

@pbadenski
Created February 28, 2017 16:49
Show Gist options
  • Save pbadenski/a4ce272dfdcb517974c3d01682395443 to your computer and use it in GitHub Desktop.
Save pbadenski/a4ce272dfdcb517974c3d01682395443 to your computer and use it in GitHub Desktop.
Priority based task execution in JS using WebWorker
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