General Solution For Pre-emptive Background Work Scheduling On Javascript
Here is the scenario: When my web app starts, I want to load data from several tables in local storage (using indexedDB). I delegate this work to a web worker. It will load each t
Solution 1:
The Worker may use an asynchronous queue that contains all the tables to be loaded and is sorted after a certain priority, so you can priorize certain tables and they get sorted to the front of the table. As you havent shown a real implementation here is a more generalized version:
classAsyncPriorityQueue{
constructor(task){
this.task = task;
this.queue = [];
}
push(element, priority = 0){
const pos = this.queue.findIndex(el => el.priority < priority) + 1;
this.queue.splice(pos, 0, {element, priority});
if(this.running) return;
this.running = true;
this._run();
}
prioritize(element, priority = 10){
const pos = this.queue.findIndex(el => el.element === element);
if(pos != -1) this.queue.splice(pos, 1);
this.push(element, priority);
}
async _run(){
while(this.queue.length)
await this.task(this.queue.shift().element);
}
}
Note: If the task is not asynchronous you should use sth like setTimeout(next, 0)
to allow the process messaging to interrupt it...
A sample implementation could be an image loader:
classImageLoaderextendsAsyncPriorityQueue {
constructor(){
super(functiontask(url){
const img = newImage();
img.src = url;
returnnewPromise(res => img.onload = res);
});
}
}
const loader = newImageLoader;
loader.push("a.jpg");
loader.push("b.jpg", 1); // a bit more important// Oh, wait:
loader.prioritize("a.jpg");
Post a Comment for "General Solution For Pre-emptive Background Work Scheduling On Javascript"