Apparently, using window.postMessage is a preferred way to queue an async javascript callback over window.setTimeout(fn, 0)
across all modern browsers. I could not find a similar comparison between window.postMessage and MessagePort.postMessage (using the same MessageChannel for sending and receiving messages asynchronously). Has anyone seen or done any timing? Does MessagePort.postMessage work for this purpose at all (where available)?
[EDITED] MessagePort.postMessage
does work for this, but window.postMessage
remains a preffered way, IMO (see my answer).
[UPDATE] Added a test for
setImmediate
and a JSFiddle. Related, there's a cross-browser implementation ofsetImmediate
and ASAP library used by Q for a promise resolution/rejection.I went ahead and did some timing, using a modified version of David Baron's code, the results are below:
setTimeoutMC
- usingMessageChannel
setTimeoutPM
- usingwindow.postMessage
setTimeout(0)
- usingsetTimer
IE10:
Chrome v29.0.1547.66:
Clearly, window.postMessage is the winner here (considering the level of existing cross-browser support for it). The looser is
window.setTimeout(fn, 0)
and should be avoided wherever possible.Code: