Re: Synchronous postMessage for Workers?

On Fri, Nov 18, 2011 at 12:18 PM, David Levin <levin@chromium.org> wrote:

> The primary use case is one in which messages sent to
> DedicatedWorkerGlobalScope are reserved for synchronous messaging.
>

Mostly, yes, or otherwise dealing with unrelated messages coming in while
you're waiting for a response.

It's possible to safely use async and sync message receipt on the same
channel.  For example,

onmessage = function(e)
{
    if(e.data.message == "pause")
    {
        msg = waitForMessage();
        // assert(msg.message == "continue");
    }
}

and in the main thread,

worker.postMessage({message = "pause"});
alert("The worker is currently paused and waiting to be continued");
worker.postMessage({message = "continue"});

Once you send "pause", events and timers in the worker will be deferred
until you resume it.  Since messages are delivered in order, this is
guaranteed to work.

(By the way, the above isn't why I prefer this API; I prefer it because it
avoids adding more messaging mechanisms and it creates a simpler API.  The
above is just an interesting way it might be used.)

-- 
Glenn Maynard

Received on Friday, 18 November 2011 17:56:45 UTC