V2EX = way to explore
V2EX 是一个关于分享和探索的地方
现在注册
已注册用户请  登录
jakwings
V2EX  ›  Node.js

什么时候该推荐用 setTimeout(fn, 0) 而不是 setImmediate(fn) ?

  •  
  •   jakwings · 2014-04-10 23:21:12 +08:00 · 3745 次点击
    这是一个创建于 3665 天前的主题,其中的信息可能已经有所发展或是发生改变。
    按照官方文档的说明,这两个 API 是使用两个独立的 event queue 的,而且后者是保证了执行顺序的,除此之外似乎已经没有任何太大的区别。若不考虑将模块移植到浏览器端,那什么时候该用前者呢?
    9 条回复    1970-01-01 08:00:00 +08:00
    jsonline
        1
    jsonline  
       2014-04-10 23:49:37 +08:00   ❤️ 1
    1. setImmediate 不是标准用法,只在 IE 10+ 和 NodeJS 上实现。

    2. setTimeout 0 的即时性不如 setImmediate
    setTimeout(fn, 0) can potentially be used, however as it is clamped to 4ms per the HTML spec, it does not make for a suitable polyfill for the natural immediacy of setImmediate.

    所以,在浏览器上用前者,在 Node 上用后者。

    参考 https://developer.mozilla.org/en-US/docs/Web/API/Window.setImmediate
    jsonline
        2
    jsonline  
       2014-04-10 23:58:13 +08:00   ❤️ 1
    关于 4ms:
    Timers can be nested; after five such nested timers, however, the interval is forced to be at least four milliseconds.

    参见 http://www.whatwg.org/specs/web-apps/current-work/multipage/timers.html#timers
    jakwings
        3
    jakwings  
    OP
       2014-04-11 00:04:14 +08:00
    @jsonline 谢了~
    我看到有人在纯 NodeJS 的模块里用 setTimeout 而不是 setImmediate 感觉有点奇怪,所以好奇会不会是因为两者分别占两个 event queue 会有什么特别的用途。看来 NodeJS 是该坚持用 setImmediate 了。
    yyfearth
        4
    yyfearth  
       2014-04-11 00:24:03 +08:00   ❤️ 1
    @jakwings setImmediate 是新支持的 所以NodeJS 里面有setTimeout不奇怪
    jakwings
        5
    jakwings  
    OP
       2014-04-11 01:53:04 +08:00
    @yyfearth 嗯,发现 0.8.x 不支持。
    yangff
        6
    yangff  
       2014-04-11 08:46:39 +08:00
    话说我一般用process.nextTick哎?
    jakwings
        7
    jakwings  
    OP
       2014-04-11 09:08:57 +08:00
    @yangff process.nextTick 有更专门的用途,我觉得用来取代 setImmediate 有点大材小用了……
    yangff
        8
    yangff  
       2014-04-18 08:13:39 +08:00
    @jakwings 球详细?
    PS:v2ex的推送延迟有点高啊。。
    jakwings
        9
    jakwings  
    OP
       2014-04-18 08:37:57 +08:00   ❤️ 1
    @yangff nextTick 会让回调函数在当前线程的下一个事件回调函数被调用前执行。这样我们就可以在链式风格的函数调用中即时绑定任务,然后再为任务提供回调函数,而且不怕任务在提供回调函数之前就开始执行。
    http://nodejs.org/api/process.html#process_process_nexttick_callback
    关于   ·   帮助文档   ·   博客   ·   API   ·   FAQ   ·   我们的愿景   ·   实用小工具   ·   3125 人在线   最高记录 6543   ·     Select Language
    创意工作者们的社区
    World is powered by solitude
    VERSION: 3.9.8.5 · 27ms · UTC 14:42 · PVG 22:42 · LAX 07:42 · JFK 10:42
    Developed with CodeLauncher
    ♥ Do have faith in what you're doing.