Introduction to JavaScript messaging mechanism

Source: Internet
Author: User
Tags set time sleep function

The language of JavaScript itself is built on a message mechanism, so it is easy to handle asynchronous callbacks and various events. This concept is different from the Common Programming language Foundation, so many people who have just touched JavaScript have no idea. JavaScript is a message that enables multiple transactions to be processed at the same time, not to hang yourself in a message.
Often you see the question "Does JavaScript have a sleep function?" "," How do I get the above function to execute and then execute the following function? "That's because you didn't understand the message mechanism." JavaScript is single-threaded, and if there is a sleep function, the entire page stops rendering during sleep, and using XHR to synchronize requests for a large file will happen, so it is unscientific to sleep in JavaScript! JavaScript is, of course, the same as other programming languages, where code runs from top to bottom, and the function above must be executed before executing the following function. I know that the question that the questioner encounters is that there is an asynchronous callback in the function above, and that the following function needs to be run after the asynchronous callback is over, which is the mechanism of not understanding the message.
So, what's the news? This is for beginners, I do not start from the thread of the message mechanism to introduce. To put it simply, every message can be understood as a snippet, with a lot of messages being placed in a message queue, and they are executed sequentially, unable to process two messages at a time. A large part of these messages are system messages, which are typically used to handle page rendering. For example, when you drag the scroll bar, the scrollbar event is triggered, and the page needs to be redrawn, these events, redraws, and messages.
We can of course also use functions such as settimeout to add their own messages to and from the message queue, sometimes referred to as timer events. The function of settimeout is to put a function as a new message in the message queue. Of course, you can also specify a delay time to put the message queue by setting its second parameter. SetInterval, however, adds the specified function as a message to the message queue every other set time. Messages added to the message queue are not processed immediately, because messages in Message Queuing are also processed sequentially. For example, a code like thissetTimeout(function(){
  alert("timeout消息中执行的");
});
alert("初始化消息中执行的");
When code parsing is complete, an initialization message is generated to execute the code. First executes the first line of settimeout, which does not execute the anonymous function specified as a parameter, but adds the function as a message to the message queue. After the alert is executed, the output is executed in the initialization message, and the message is initialized and the run is finished. And then the next message, it's not necessarily the timeout message we added, because Message Queuing might have added a lot of page rendering related messages before initializing the message, we just added the timeout message at the end of the message queue. However, when these system messages are processed, the timeout message that we added will be processed and output "timeout message execution". This is the concept of asynchronous callbacks, even with Ajax, such asvar xhr=new XMLHttpRequest;
xhr.open("GET","?",true);
xhr.send();
xhr.onreadystatechange=function(){
  if(xhr.readyState<4)return;
  alert(xhr.responseText);
};
alert("Ajax还没完成呢?");
Perhaps someone would be surprised why the event was bound after send? Should I add the event first and then send it again? In fact, the XHR object uses other threads, which involves a bit of cross-thread communication, and if you're not interested, you can skip this paragraph. A delegate is required to access data across threads, or a data conflict occurs, and a delegate is actually a thread that sends a message to another thread. After the send is executed, even if the server returns data faster than I do (it is generally not possible), the XHR thread needs a delegate to trigger the onReadyStateChange event that triggers the main thread XHR object, and the main thread is currently busy, and it is processing the initialization message. It is only when the initialization message is processed that the child thread's delegate is processed, and when the initialization message is processed it means that onreadystatechange is bound, so it is always executed before the event Cheng the XHR line.
The code runs from top to bottom, so there's no more code to run after the code above runs out. But this Ajax example can easily give the illusion that Ajax is not the end of the implementation of the final alert. Actually the above code has finished their work, and the last alert has 4 statements before it right? The first sentence creates a Xhr object, the second sentence sets the relevant parameters of the XHR request, the third sentence sends the request, and the fourth sentence binds the event. Isn't all of this work done? Not complete is not the code above, but the entire AJAX logic business. If you want the entire logical business to be processed and then execute the last alert, you should find the end of the entire logical business, such as another alert in the above code. Not only is Ajax, many logical businesses require multiple messages to be processed together, such as the animated effect of settimeout implementation.
JavaScript is like this, itself is single-threaded, through the message to implement multiple transactions simultaneously processing. Don't hang yourself in a message.

Original link: http://www.web-tinker.com/article/20294.html

Introduction to JavaScript messaging mechanism

Related Article

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.