Introduction to Event-Driven Programming
Event driven programming is the programming paradigm in the field of computer science. In this type of programming paradigm, flow of execution is determined by the events like user clicks or other programming threads or query result from database. Events are handled by event handlers or event callbacks.
Event callback is a function that is invoked when something significant happens like when click event is performed by user or the result of database query is available.
I/O Programming V/S Event-Driven Programming
I/O programming blocks the flow of execution of program until the process finishes. The below example is written in both pattern I/O programming(first one) and Event driven programming.
I/O programming pattern:
result = query(‘SELECT * FROM posts WHERE id = 1’);
myResult(result);
This query requires that the current thread or process wait until the database layer finishes processing it.
Event driven programming pattern:
query_finished = function(result) {
myResult(result);
}
query(‘SELECT * FROM posts WHERE id = 1’, query_finished);
Here you are first defining what will happen when the query is finished and storing that in a function named query_finished. Then you are passing that function as an argument to the query.When it’s finished, the query will invoke the query_finished function, instead of simply returning the result.
This style of programming — whereby instead of using a return value you define functions that are called by the system when interesting events occur — is called event-driven or asynchronous programming. This is one of the defining features of Node. This style of programming means the current process will not block when it is doing I/O. Therefore, several I/O operations can occur in parallel, and each respective callback function will be invoked when the operation finishes.
Event Loop :
Event driven programming is accompanied by the Event loop. An Event Loop constructs that performs two functions in a continuous loop.
- Event Detection
2. Event handler triggering.
In any run of event loop, it has been detected which event is happened.Then , when events happens, the event loop must determine the event callback and invoke it.
The Event loop is one thread running inside one process, which means that when event happens, the event handler run without interruption.
There is at most one event handler is running at any given time and any event handler will run and complete his task without any interruption.