[Bug 15007] Add an API to queue a task

https://www.w3.org/Bugs/Public/show_bug.cgi?id=15007

--- Comment #18 from Glenn Maynard <glenn@zewt.org> 2011-12-05 15:57:40 UTC ---
Clearing onmessage isn't necessary for GC.  Once no messages are in the message
queue, the ports can be collected, since neither of the ports are reachable
from live code.

We should disentangle the message ports, though:

var queueTask = function(task)
{
    var mc = new MessageChannel();
    var args = [].slice.call(arguments, 1);
    mc.port1.onmessage = function() { task.apply(task, args); };
    mc.port2.postMessage(null);
    mc.port2.close();
}
queueTask(function(arg) { console.log(arg, this) }, "test");

However, I notice a subtle problem: each MessageChannel acts as its own task
source.  This means that messages sent using this function are not guaranteed
to execute in order, since the order task sources are processed isn't
specified.  Tasks are ordered only *within* a single task source.  Chrome just
happens to do what we want.

We can work around that here by reusing a single MessageChannel:

var _taskChannel = new MessageChannel();
var _taskQueue = [];
_taskChannel.port1.onmessage = function()
{
    var task = _taskQueue[0][0];
    var args = _taskQueue[0][1];
    _taskQueue.shift();
    task.apply(task, args);
};

var queueTask = function(task)
{
    var args = [].slice.call(arguments, 1);
    _taskQueue.push([task, args]);
    _taskChannel.port2.postMessage(null);
}
queueTask(function(arg) { console.log(arg, this) }, "test1");
queueTask(function(arg) { console.log(arg, this) }, "test2");
queueTask(function(arg) { console.log(arg, this) }, "test3");

-- 
Configure bugmail: https://www.w3.org/Bugs/Public/userprefs.cgi?tab=email
------- You are receiving this mail because: -------
You are the QA contact for the bug.

Received on Monday, 5 December 2011 15:57:47 UTC