As we all know, JavaScript code can only be executed on one thread, that is, a single thread. The code executed on a single thread has a characteristic: it can only be executed sequentially. If there is time-consuming operation logic in the code, it is likely that It will cause the browser to freeze.
So why is JavaScript designed as a single-threaded model?
The designers of Javascript believe that if javascript is designed to be multi-threaded, it will greatly increase the complexity of the program. For example: if there are two threads, one thread is responsible for creating a button button, and the other thread Delete this button. Due to the uncertainty of the order of multi-thread execution, this button may or may not appear on the page, which will cause great trouble to developers. Therefore, for the sake of simplicity, JavaScript was designed as a single-threaded model from the beginning, which is the core feature of JavaScript.
In order to solve the single-thread limitation of javascript, the tasks in the javascript program are divided into: synchronous tasks and asynchronous tasks
Synchronization tasks: refers to tasks that are queued for execution and are not suspended by the javascript engine on the main thread. The next task will only start execution after the previous task is completed.
Asynchronous tasks: refers to some time-consuming tasks (such as IO requests), which are placed in the task queue by the JavaScript engine. Because these tasks are not on the main thread, these tasks It will not be executed until it is scheduled to the main thread (such as a callback function in ajax).
So where does the task queue come from?
In fact, when JavaScript is executed, in addition to the main thread, the JavaScript engine will also create some task queues, which contain some asynchronous tasks that the current program needs to process, such as the asynchronous callback function of ajax. Functions in setTimeout and so on. When all tasks on the main thread are executed, the engine will check in each task queue to see if there are tasks that meet the execution conditions. If so, it will be scheduled to the main thread for execution.
The above is the detailed content of Javascript asynchronous task principle (picture and text). For more information, please follow other related articles on the PHP Chinese website!