Event Loop

suggest change

Blocking Operation Example

let loop = (i, max) => {
  while (i < max) i++
  return i
}

// This operation will block Node.js
// Because, it's CPU-bound
// You should be careful about this kind of code
loop(0, 1e+12)

Non-Blocking IO Operation Example

let i = 0

const step = max => {
  while (i < max) i++
  console.log('i = %d', i)
}

const tick = max => process.nextTick(step, max)

// this will postpone tick run step's while-loop to event loop cycles
// any other IO-bound operation (like filesystem reading) can take place
// in parallel
tick(1e+6)
tick(1e+7)
console.log('this will output before all of tick operations. i = %d', i)
console.log('because tick operations will be postponed')
tick(1e+8)

In simpler terms, Event Loop is a single-threaded queue mechanism which executes your CPU-bound code until end of its execution and IO-bound code in a non-blocking fashion.

However, Node.js under the carpet uses multi-threading for some of its operations through libuv Library.

Performance Considerations

Node.js non-blocks IO because it offloads the work to the operating system kernel, and when the IO operation supplies data (as an event), it will notify your code with your supplied callbacks.

Feedback about page:

Feedback:
Optional: your email if you want me to get back to you:


Performance:
* Event Loop

Table Of Contents
1 npm
41 cli
43 grunt
59 Hack
64 ES6
67 Redis
69 MongoDB
86 MongoDB
87 Lodash
91 CORS
93 Performance
105 N-API
108 Require