1. The queue

  • Fifo data structure
  • Js does not have queues, but you can implement queues using arrays
    • The teampush()
    • Out of the teamshift()

const queue = []; / / the team queue. Push (1); // [1] queue.push(2); // [1, 2] // const item1 = queue.shift(); // 1 const item2 = queue.shift(); / / 2Copy the code

2. What scenarios use queues

  • Need to beFirst in first outThe scene
  • For example: canteen queue for meals, JS asynchronous task queue, calculate the number of recent requests

2.1 Scenario 1: Queue for lunch in the canteen

  • Only one window is left in the canteen, where students queue up for meals like Spring Festival travel rush
  • First in, first out, order guaranteed

2.3 Scenario 2: Task Queue in JS Asynchronism

  • JS is single-threaded and cannot handle concurrent tasks in asynchro
  • Use task queues to process asynchronous tasks sequentially

2.3 Scenario 3: Calculating the Number of recent Requests

  • New request to join the team, 3000ms before the request to leave the team
  • The length of the queue is the number of recent requests

3. LeetCode:933. Number of recent requests

To be answered, please pay attention to

4. Front-end and queue: task queue in JS async

Wikipedia defines it as: An event loop is a programming construct that waits for and dispatches events or messages in a program.

4.1 Main Thread and Task Queue

In JavaScript runtime, in addition to a running main thread, the engine also provides a task queue of various asynchronous tasks that need to be handled by the current program. (In fact, there are multiple task queues depending on the type of asynchronous task. For ease of understanding, assume that there is only one queue.

First, the main thread performs all synchronization tasks. When all the synchronous tasks are completed, the asynchronous tasks in the task queue are viewed.

If the condition is met, the asynchronous task is re-entered into the main thread to begin execution, and it becomes a synchronous task. The next asynchronous task enters the main thread to start execution. Once the task queue is empty, the program ends execution.

4.1 Asynchronous tasks are usually written as callback functions

Once the asynchronous task re-enters the main thread, the corresponding callback function is executed. If an asynchronous task does not have a callback function, it will not enter the task queue, that is, it will not re-enter the main thread, because there is no callback function to specify the next operation.

4.2 Event Loop

How does a JavaScript engine know if an asynchronous task has a result, if it can get into the main thread? The answer is that the engine is constantly checking, over and over again, to see if pending asynchronous tasks are ready to enter the main thread once the synchronous task has finished. This Loop checking mechanism is called an Event Loop.