Node.js and the tick

One of the popular searches on the internet about getting into programming with NodeJS is the keyword “tick”, presumably from all the talk about non-blocking I/O related to NodeJS.

Coming from an E.E. background and having studied around Microprocessors such as 8080, Z80, 8086 and 68000, I look at the concept of “tick” with fond familiarity.

The activities we see in our daily lives such as a school are governed by a time schedule, typically synchronized by the school bell. The ringing of the bell signifies start of a class, recess, lunch or end of a class session. In other words, the school bell synchronizes the various “events” that take place in a school. This allows the school to carry out multiple activities with hundreds of students in a methodical manner.

In case of a C.P.U or a Microprocessor it is the “clock cycle” that keeps its activities, such as reading from the memory, in sync and making sure that there are no collisions on the “bus”. In this case each clock cycle is called a “tick”.  A C.P.U with a system clock of 1GHz would translate to 1000,000,000 clock cycles or “ticks”.  It can choreograph hundreds of thousands of operations effortlessly .

A C.P.U. also maintains a table of instructions(machine code) and their respective “ticks”. For example an “add” operation might need 5 clock cycles or ticks. This allows a C.P.U to sequentially and accurately synchronize the execution of instructions and its other activities without losing a “tick”.

So, how does all this relate to NodeJS? 

It is common knowledge that NodeJS is a set of libraries that sits on top of two subsystems. Google Chrome’s V8 JavaScript engine and Libuv.

It is “Libuv” that provides NodeJS the power of a multi platform “evented” model that it is known for. It includes an event loop which processes events or activities that occur from time to time. This event loop like the C.P.U. synchronizes its affairs using an internal clock. To put it simply, it picks an event for handling at every “tick” or “ticks”.

The event loop does not process or handle the event itself but delegates it to other subsystems of the operating system that it is running on. This allows it to process(or delegate) many events in the very small number of ticks.

The clock being highly accurate and regulated, the event loop and thereby NodeJS can flawlessly  provide the efficient “evented” I/O that we have all grown to love.