If the interview answers JS 's operating mechanism, you might say: "Javascript events and asynchronous tasks, the synchronization task encountered in the execution stack execution, and encountered the asynchronous task in the task queue, Wait until the execution stack finishes executing the events in the task queue. "But can you tell the reason behind it?"
first understand the relevant concepts
Threads and Processes
Process: A unit of system resource allocation and scheduling. A running program corresponds to a process. A process includes memory and system resources that are used by programs and programs that are running.
Thread: A thread is the performer of a process, and a process can open at least one thread (the main thread) or multiple threads.
Synchronous and asynchronous
synchronous and asynchronous attention : message ( result ) communication mechanism
synchronization : After a call is made , the call does not return until the result is obtained. But once the call returns, it gets the return value
Async : The call returns directly after the call is made, and no result is returned. But the result is given by the callback function, as to when to give, do not know. (This callback function must be executed only after the current JS execution)
blocking and non-blocking
blocking and non-blocking concerns the state of the program as it waits for the result to be called .
blocking call : The current thread is suspended until the call results are returned. The calling thread will not return until the result is obtained.
non-blocking call : The call does not block the current thread until the result is not immediately available.
Why is JavaScript a single thread?
javascript is single threaded , the program is arranged in order, The front must be handled well and the latter will be executed. JavaScript was originally designed to be simple user interaction, operation Dom and so on, so this language should revolve around single threaded to design appears complex synchronization problem.
because JavaScript is single-threaded, and we can use asynchronous programming for time-consuming or uncertain operations, because asynchronous can implement non-blocking operations. Of course you can use it . HTML5 a standard Web Worker. This article does not discuss, refer to MDN document in detail : click here
Since JS is a single-threaded execution , who is going to poll the big task queue? isn't that a contradiction?
JS's
Single Thread
is it contradictory to async?
No contradiction!!! First of all remember this sentence:Js execution is a single thread, but the browser is multithreaded .
1)
JS's single thread
A browser process has only one JS execution thread, there will only be one piece of code executing at the same time
2)
Browser
is a
Multithreading
Consult the material, some articles also say is the module, this article in the browser is multithreading , it has the following resident thread:
Render engine thread: Responsible for rendering the page
JS engine Thread: Responsible for The parsing and execution of JS (the main thread of this article refers to the JS engine thread)
Timer Trigger Thread: Handles timed events, such as SetTimeout, setinterval
Event Trigger thread: Processing DOM Events
Asynchronous http request thread: Processing http requests
......
Browser is a Js 's scenario, the browser itself is a typical GUI worker thread (GUI worker threads are implemented as event handlers in most systems to avoid blocking interactions ). So the browser is eventdriven, and many of the behaviors in thebrowser are asynchronous, creating events and putting them into the task queue.
Because JavaScript is a single thread, it requires an asynchronous completion of time- consuming or indeterminate operations , which are executed by other threads of the browser, which form an asynchronous event driver. Asynchronous event drivers are often done by two or more resident threads in the browser. For example , an AJAX asynchronous request is made by the JS execution thread and the asynchronous HTTP request thread , which the event triggers the thread to do together .
Event Loops
mechanism (Event Loop)
related
Concept
Stack
A function call forms a stack frame.
1 function foo (b) { 2 let A = 10 3 return A + B + 11; 4 } 5 6 function bar (x) { 7 let y = 3 8 return foo (x * y); 9 } 10 11 Console.log (Bar (7));
when Bar is called , the first frame is created and the frame contains the bar 's parameters and local variables.
when bar calls foo , the second frame is created and pressed above the first frame, and the frame contains foo 's parameters and local variables.
when Foo returns, the topmost frame is ejected from the stack ( The call frame of the bar function is left).
when bar returns, the stack is empty.
Heap
Objects are allocated in a heap, one to represent a large, non-organized area in memory.
Each thread has only one stack, and each program has only one heap.
Queue
a The JavaScript runtime contains a pending message queue. Each message is associated with a function.
When the stack is empty, a message is fetched from the queue for processing. This process involves invoking the function associated with the message.
When the stack is empty again, it means that the message processing is finished.
Task Queue
(
Message Queuing
)
The task queue is a FIFO data structure, and when the main thread executes the stack, the callback function of the task queue automatically enters the main thread. The tasks are divided into two types :
1 . Synchronous Task : A task that is queued on the main thread for execution . the last task can be performed only after the previous task has been executed .
2, Asynchronous Task : The task does not enter the main thread, but into the task queue . When the execution stack is emptied, the tasks in the task queue are not executed.
run mechanism for asynchronous execution
Because JavaScript can execute only one piece of code at a time (because of its single-threaded nature), each of these blocks "blocks" the progress of other asynchronous events. This means that when an asynchronous event occurs (such as a mouse click, Timer trigger, or XMLHttpRequest completion), it will queue up for execution later (the determination of the actual occurrence of this queue will vary depending on the browser to the browser).
1, All synchronization tasks are executed on the main thread, forming a stacks .
2. When an asynchronous task isencountered (IO device operation, etc. ), an event is added to thetask queue that corresponds to the callback function of the asynchronous task.
3, the stacks in the execution of all synchronization tasks, the system will read the task queue, into the execution stack, start execution.
4 . The main thread repeats the third step continuously. This forms the event loop.
Conclusion: Javascript 's events are divided into synchronous tasks and asynchronous tasks, the synchronization task is executed in the execution stack, and the asynchronous task is put into the task queue until the execution stack executes and then executes the event in the task queue.
events and callback functions
the concepts necessary to explain
- worker thread: This is a general term for a thread other than the JS engine thread .
- callback function : Call another function in one function. This refers to the asynchronous scenario in order to not block the code that is hung up by the main thread.
- The main thread reads the task queue, which reads what events are inside and executes the corresponding callback function.
When the worker thread finishes a task, it adds an event to the task queue. The complete task here is to complete the operation (click,mouse,touch, Ajax Data is fully requested back ... ) does not refer to the callback function that executes it
function () { console.log ("RoRo")}
As of the above code, only the click is manipulated ,but no callback function is executed to print RoRo
Event Loops
The event Loop is the process by which the main thread repeatedly takes messages (events) from the task queue and executes the corresponding callback function .
, when the main thread runs, the heap (heap) and Stack (stack) are generated, andthe code in the stack calls various external APIs, which add various events to the task queue ( Click,load,done). As long as the code in the execution engine stack finishes executing, the main thread reads the task queue and executes the callback function that corresponds to those events.
Timer
First of all, refer to this article of the foreigner:How-javascript-timers-work, the implementation of the timer and details.
setTimeout ()
How do you do it?
SetTimeout (function () { console.log (' a '5000)
When the Javascript execution engine ( main thread) runs, it generates heaps and stacks. The code in the program goes into the stack and waits for execution when the SetTimeout () method is called, and the delay method is processed under the browser 's timer thread when the SetTimeout method executes after 5 seconds , the trigger condition is reached , and the method is added to the task queue used for the callback .
When the execution engine's execution stack is empty, the execution engine starts polling to check whether the task queue has tasks that need to be executed, and when it checks to the delay method that already conforms to the execution condition , the delay method Console. Log ('a') is pressed into the execution stack , the engine discovery calls the log () method, and then log () method into the stack. Then execute the stack sequentially, output ' A ', empty the execution stack , and complete the execution.
setTimeout (FN
, 0
)
is it done immediately?
in the JavaScript authoritative guide: When the delay time of SetTimeout is set to 0 , the callback function does not execute immediately, but instead enters the event queue.
function () { setTimeout(function () { console.log (' a ') 0);}
SetTimeout (fn,0) means to specify that a task executes as early as possible at the idle time of the main thread . It is added to the task queue, so it will not be executed until the previous event in the Synchronization task and task queue has been processed .
The HTML5 standard specifies that the minimum value of the second parameter of setTimeout () must not be less than 4Ms, and if it is below this value, it will automatically increase. The old version of the browser allows the minimum interval to be set to 10ms. Detailed reference MDN Documentation: Minimum latency and timeout nesting
So settimeout (fn,0) is not executed immediately. If you want to implement 0MS timeout can be used Window.postmessage (), this article is not discussed.
Two classic interview questions:
a) What does the following code output?
function foo () { console.log (' a ') setTimeout (function () { console.log (' B ') ); ( Let i = 0; i < 10000; i++) { foo ()}
execution result : First all output a, the middle waits 500ms, then all output B. is personal understanding, inappropriate place please point out!
II)a
Jax is the asynchronous request really asynchronous?
1, JS execution thread (main thread) initiates an asynchronous request , the browser will open a new HTTP request thread to execute the request, continue to perform the remaining tasks in the stack,
2. In a new thread (the HTTP request thread), the browser handles the execution of the other tasks as expected while the request is executing.
3 . at some point in the future , when the data is fully requested , the event-triggering thread monitors the HTTP request that was previously initiated , The specified callback function is placed in the task queue.
4, when the browser stacks idle , to scan the task queue of the callback function, and then press into the execution stack processing.
so: The AJAX request is asynchronous . a new thread request is opened by the browser, and the event callback is placed The Event Loop task queue waits for processing. for A detailed example, you can refer to the MDN document's description of Ajax : Synchronous and asynchronous
Myth: Event loops like stacks or queues
Incidentally, the event loop involves a queue-like structure and does not handle the task in the same way as a stack. The event loop is divided into multiple stages as a process, each of which handles some specific tasks, and each stage polls the schedule. These stages can be timer processing,Dom event handling,Ajax Asynchronous processing ...
Conclusion
The JavaScript engine has only one thread, forcing asynchronous events to be queued for execution,and the JavaScript language 's event loop is the browser's handling and behavior. In addition, this article is my personal study notes , the entire combination of personal understanding, in some places is not rigorous, if there are errors, I hope to point out.
Talking about event Loop from JavaScript single thread