Although more and more websites are being developed using AJAX technology, building a complex AJAX application is still a problem.
What are the main reasons for these difficulties? Is it an asynchronous communication issue with the server? Or is it a GUI programming issue? Usually these two tasks are completed by desktop programs, so why is it so difficult to develop an AJAX application that can achieve the same function?
Everyone knows that JavaScript is executed in a single thread, but it can also execute a method regularly through setTimeout or setInterval. Through Ajax, you can continue to execute the main logic after sending a request to the server but not receiving a response. How this is done is discussed below.
First look at the following piece of code:
<html> <body> <script type="text/javascript"> function printHello() { console.time("hello"); } function printHello1() { console.timeEnd("hello"); } setTimeout(printHello,1000); setTimeout(printHello1,5000); function wait(time) { var now = Date.now(); while(Date.now() - now < time) { } } wait(5000); </script> </body> </html>
The execution result of the above code is
hello: 0.124ms
As can be seen from the code, printHello and printHello1 are executed almost simultaneously. For a multi-threaded model, the execution interval should be 4000ms.
The reason for the above is that setTimeout only pushes the event into the queue at the time point, rather than executing it immediately. The specific timing of execution depends on the browser's idleness.
In fact, although javascript is single-threaded, browsers are multi-threaded. A typical browser has the following threads:
javascript engine thread
Interface rendering thread
Browser event trigger thread
Http request thread
Javascript single thread refers to the JavaScript engine thread processing its event queue in a single thread, and the browser is event-driven. Many events are asynchronous, such as mouse click events, setTimeout, and Ajax callback events. When these events occur , the browser will put these events into the execution queue and wait for them to be executed when the browser is idle.
In addition, it is worth mentioning that the ajax call is indeed asynchronous. The browser will start a new thread to send a request to the server. If a callback event is set, the callback event will be placed in the event based on the server return status. queue.
The above is my understanding of JavaScript multi-threading. My personal understanding is limited. I also hope that all heroes can provide valuable opinions and learn together. I hope the above introduction will be helpful to everyone.