wip: add more questions

chore/javascript
Arik Chakma 1 year ago
parent ff000c87ed
commit 802b84ad79
  1. 26
      src/data/question-groups/javascript/content/event-loop.md
  2. 10
      src/data/question-groups/javascript/javascript.md

@ -0,0 +1,26 @@
The Event loop has two main components: the Call stack and the Callback queue.
## Call Stack
The Call stack is a data structure that stores the tasks that need to be executed. It is a LIFO (Last In, First Out) data structure, which means that the last task that was added to the Call stack will be the first one to be executed.
## Callback Queue
The Callback queue is a data structure that stores the tasks that have been completed and are ready to be executed. It is a FIFO (First In, First Out) data structure, which means that the first task that was added to the Callback queue will be the first one to be executed.
## Event Loop's Workflow:
1. Executes tasks from the Call Stack.
2. For an asynchronous task, such as a timer, it runs in the background. JavaScript proceeds to the next task without waiting.
3. When the asynchronous task concludes, its callback function is added to the Callback Queue.
4. If the Call Stack is empty and there are tasks in the Callback Queue, the Event Loop transfers the first task from the Queue to the Call Stack for execution.
```js
setTimeout(() => console.log('Hello from the timer'), 0);
console.log('Hello from the main code');
```
1. `setTimeout` is processed, and because it's asynchronous, its callback is placed in the Callback Queue.
2. The next line, `console.log("Hello from the main code")`, is logged immediately.
3. Although the timer duration is 0 milliseconds, its callback has to wait until the Call Stack is empty. After the main code logs, the callback is moved from the Callback Queue to the Call Stack and executed.
4. The result is "Hello from the main code" being logged before "Hello from the timer".

@ -288,4 +288,14 @@ questions:
topics:
- 'Core'
- 'Beginner'
- question: What is Event Loop in JavaScript?
answer: The Event loop is one the most important aspect to understand in JavaScript. It is the mechanism that allows JavaScript to perform non-blocking operations. It is the reason why we can use asynchronous code in JavaScript. The Event loop is a loop that constantly checks if there are any tasks that need to be executed. If there are, it will execute them. If there are no tasks to execute, it will wait for new tasks to arrive.
topics:
- 'Core'
- 'Advanced'
- question: How does Event Loop work in JavaScript?
answer: event-loop.md
topics:
- 'Core'
- 'Advanced'
---

Loading…
Cancel
Save