Event-driven single-thread model, all JavaScript code is executed in one thread, and the JavaScript thread takes out one event at a time from the event queue for execution.
Rule 2In addition to the javascript thread, the host also has timer threads (setInterval and setTimeout will trigger the execution of these two threads), browser event triggering threads (this thread will trigger onclick, onmousemove and other browser events), and AJAX requests Threads; all events (callbacks) triggered by these threads will be added to the end of the event queue.
Rule 3When the browser loads the HTML document, it will treat all the js code of the current HTML as the first event in the event queue, and events (callbacks) triggered by other threads will be added to the end of the event queue.
Rule 4The execution time of the callbacks in setTimeout and setInterval must be greater than the number of seconds specified for them.
Browser rendering threadIf the javascript execution thread executes the A event and modifies the DOM during the execution of the A event, these DOM modifications will not be immediately reflected on the interface. Instead, when the A event is completed, the javascript thread will be blocked. At this time, the browser rendering thread will render the modification result of the DOM. After the browser rendering thread completes execution, the javascript thread will continue to run.
Code example