2 ms·
That's essentially re-queuing a repeating task, and the task is to process blocks of work incrementally until completion. This is not unlike what happens in an
by astrodust 18y ago
That's essentially re-queuing a repeating task, and the task is to process blocks of work incrementally until completion. This is not unlike what happens in an operating system that uses cooperative multitasking.
You might consider a refinement of the pattern where doSomeWork() returns true if the work queue still has things left, or false if it is finished. As a matter of convenience, doSomeWork() should handle finishing as a final task to avoid the redundant isDone() check.
A slight refactoring could be:
processor = function() {
if (processWork())
window.setTimer(processor, 0);
}
- IsaacSchlueter 18y agoAs I said, I simplified the expression to show all the relevant parts of the pattern in a single function. In a real application, either all the features of the pattern might be inline, or some might be delegated to other functions, or some might be omitted. Also, you can make it slightly more powerful by wrapping an object around it. I did this recently: var queue = (function () { var q = []; return { run : function run () { var fn = q.shift(); if (fn) setTimeout(function () { fn(); run(); }, 0); return this; }, push : function (fn) { q.push(fn); return this; } }; })(); so you can do stuff like this: queue.push( function () {...} ).push( function(){...} ).start();