setTimeout(0) vs window.postMessage vs MessagePort.postMessage

前端 未结 1 960
走了就别回头了
走了就别回头了 2020-12-29 15:42

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

1条回答
  •  余生分开走
    2020-12-29 16:20

    [UPDATE] Added a test for setImmediate and a JSFiddle. Related, there's a cross-browser implementation of setImmediate 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 - using MessageChannel
    setTimeoutPM - using window.postMessage
    setTimeout(0) - using setTimer

    IE10:

    2000 iterations of setTimeoutMC took 126 milliseconds.
    2000 iterations of setTimeoutPM took 190 milliseconds.
    2000 iterations of setTimeout(0) took 7986 milliseconds.
    

    Chrome v29.0.1547.66:

    2000 iterations of setTimeoutMC took 144 milliseconds.
    2000 iterations of setTimeoutPM took 81 milliseconds.
    2000 iterations of setTimeout(0) took 10589 milliseconds.
    

    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:

    
    
    
        
        
        
        
        
        
    
    
    
        
    
    
    
    

    0 讨论(0)
提交回复
热议问题