Event loop in nodejs

0
Event Loop



Event loop is the basic concept that Node JS use to execute code. When an asynchronous function is run, it will not wait for the result. Instead an event will be placed in the system event queue after the function complete, then the callback function will observe the event in the queue and run.


An event loop is often times the “main” of a program that handles events. If you have written a program you know that it will exit when it is done. Programs that run indefinitely like UI applications, video games, web servers, etc will have some form of an event loop. They can come in different flavors such as being a polling loop (check if there is an event every time it loops) or it can be handled via blocks and something triggers it to come and do it's job.
For instance, imagine you have a program running a UI. If it's idle and you look at your running processes it's likely not going to be eating up a ton of processing time by continually looping. It can either be utterly silent or it may be taking up a fraction of a percent of the CPUs time. But if you go and hit a button the program is going to wake up and do something. This is ran by an event loop. Clicking that button fired an event which got processed by the event loop which called the buttons onClick event handler.
It many application and network programming frameworks the fundamental design of a program written to utilize the framework, is around the concept of an event loop.
Conceptually such code provides hooks, that is places where their code will call into your code, for things like configuration, initialization, adding UI (user interface) elements or I/O channels (open files, networking sockets) etc. Each of these elements and channels can be associated with their own events. Any GUI (graphical UI) element could have the mouse moved over it, hovered over it, move away from it, be clicked on or double or triple clicked, etc. Menus can be clicked on, radios and check boxes can be set or cleared, text areas can have texted edited, etc. Any I/O channel could have more data input, a buffer full or empty, or some out-of-band event (errors, end-of-file).
Once the programmer has built up all these elements and channels then the event loop is called and the various callbacks are called as events come in. (Some event loops also implement polling of various non-event driven interfaces and devices).
Your code is called by the event loop. Typically it does the work, but it can also add (and remove and modify) UI elements and I/O channels.

Tags

Post a Comment

0Comments
Post a Comment (0)