NodeJS - setTimeout(fn,0) vs setImmediate(fn)

前端 未结 9 1339
暖寄归人
暖寄归人 2020-12-07 13:23

What is the difference between those two, and when will I use one over the other?

9条回答
  •  被撕碎了的回忆
    2020-12-07 13:52

    setImmediate() is to schedule the immediate execution of callback after I/O events callbacks and before setTimeout and setInterval .

    setTimeout() is to schedule execution of a one-time callback after delay milliseconds.

    This is what the documents say.

    setTimeout(function() {
      console.log('setTimeout')
    }, 0)
    
    setImmediate(function() {
      console.log('setImmediate')
    })
    

    If you run the above code, the result will be like this... even though the current doc states that "To schedule the "immediate" execution of callback after I/O events callbacks and before setTimeout and setInterval." ..

    Result..

    setTimeout

    setImmediate

    If you wrap your example in another timer, it always prints setImmediate followed by setTimeout.

    setTimeout(function() {
      setTimeout(function() {
        console.log('setTimeout')
      }, 0);
      setImmediate(function() {
        console.log('setImmediate')
      });
    }, 10);
    

提交回复
热议问题