2

the nodejs document say

Schedules "immediate" execution of callback after I/O events' callbacks and before timers set by setTimeout and setInterval are triggered. Returns an immediateObject for possible use with clearImmediate.

but I write a test code as follows:

server = http.createServer((req, res)->
  res.end()
)

setImmediate(()->
  console.log 'setImmediate'
)

setTimeout(()->
  console.log 'setTimeout'
, 0)
process.nextTick(()->
  console.log 'nextTick'
)

server.listen(8280, ()->
  console.log 'i/o event'
)

why the setTimeout always output befeore setImmediate

sundq
  • 735
  • 2
  • 9
  • 28

2 Answers2

3

SetTimeOut - This type of function will be call after set time which is 0 in your case but it follows event loop. And event loop does not grantee that it will work after 0 seconds. In fact it only guarantees that function will be called after completing set time.

But, function can be called any time after completing time when node event queue is free to take up callback function

Source to understand event loop - https://www.youtube.com/watch?v=8aGhZQkoFbQ

SetImmediate - This will get called as and when it goes to stack and does not follow cycle of callback in event loop.

double-beep
  • 5,031
  • 17
  • 33
  • 41
Dnyanesh
  • 2,265
  • 3
  • 20
  • 17
  • `which is 0 in your case` actually [according the HTML5 spec](https://developer.mozilla.org/en-US/docs/Web/API/WindowOrWorkerGlobalScope/setTimeout#Reasons_for_delays_longer_than_specified) it's 4ms at a mininum. In Node.js, [the minimum is 1ms](https://nodejs.org/api/timers.html#timers_settimeout_callback_delay_args). – Patrick Roberts Jul 07 '19 at 19:47
0

The main advantage to using setImmediate() over setTimeout() is setImmediate() will always be executed before any timers if scheduled within an I/O cycle, independently of how many timers are present.

However, if executed in the main module, the execution order will be nondeterministic and dependent on the performance of the process

see https://nodejs.org/en/docs/guides/event-loop-timers-and-nexttick/ for more information

Ewomazino Ukah
  • 2,286
  • 4
  • 24
  • 40