event loop & callback queue in Javascript
Event loop and callback queue in javascript
Javascript is single thread language, which means that the engine can take one task only,
because JS engine has only one call stack.
JS engine reads codes and add functions in call stack, after complete the function,
it removes them from call stack.
When developer makes codes in JS and activates it, JS engine reads the codes.
JS engine do interpreting the codes to bytecodes, and Virtual Machine does interpreting them
to machine codes. When codes are interpreting, the environment is called “Runtime”.
For example, Chrome uses V8 engine for JS. So, Chrome is Runtime.
Programming is judged by two concepts: Synchronous and Asynchronous.
- Syncronous : only when one task is completed, the following one is unblocked
- Ansyncoronous : you can move to another task before the previous one finishes
Javascript is syncronous language, which is slow because it waits every events until response back.
So, Chrome supports several web API to use JS code by ansyncoronous.
Ansyncoronous code can change the commands order.
For example, if there are first function and second function, second function can be activated faster than first function.
Event loop can make ansyncronous happen in JS code.
- When a first function is in callstack, first function’s callback function moves to background.
- After first function moved, second fucntion is completed in callstack.
- First function’s callback function moves to callback queue.
- Event loop looks at callstack and callback queue.
- If there is a function in callback queue and callstack is all complete, first function in callback queue moves to callstack and activate it.
ps. call stack is the same as execution stack, control stack, run-time stack, machine stack, and the stack.