In-depth understanding of synchronization and Asynchrony in JavaScript programming

Source: Internet
Author: User

One of the advantages of JavaScript is how it handles asynchronous code. Asynchronous code is placed in an event queue until all other code executes, without blocking the thread. However, writing asynchronous code can be difficult for beginners. And in this article, I will eliminate any confusion you may have.
Understanding Asynchronous Code

The most basic asynchronous functions of JavaScript are settimeout and setinterval. SetTimeout will execute the given function after a certain amount of time. It takes a callback function as the first parameter and a millisecond time as the second parameter. The following are examples of usage:

Console.log ("a" ); SetTimeout (function() {    "C"), setTimeout ( function () {    "D" ); SetTimeout (function() {    "E"  "B");

As expected, the console outputs "a", "B", and then "C", "D", and "E" after about 500 milliseconds. I use "about" because settimeout is actually unpredictable. In fact, even the HTML5 specification mentions the problem:

"This API does not guarantee that timings will run exactly as expected. The latency caused by CPU load, other tasks, etc. is predictable. ”


Interestingly, the timeout will not occur until all remaining code in the same program segment finishes executing. So if you set a timeout and execute a function that takes a long time to run, the timeout will not even start until the function finishes executing. In fact, asynchronous functions, such as settimeout and setinterval, are pressed into the queue called the event loop.

The Event loop is a callback function queue. When an asynchronous function executes, the callback function is pressed into the queue. The JavaScript engine does not begin processing the event loop until the asynchronous function finishes. This means that the JavaScript code is not multi-threaded, even if it behaves similarly. The event loop is a first in, in, Out (FIFO) queue, which indicates that callbacks are executed in the order in which they are queued. JavaScript is chosen by node as the language of development because it is so simple to write such code.

Ajax

Asynchronous JavaScript and XML (AJAX) permanently change the state of the JavaScript language. Suddenly, the browser no longer needs to reload to update the Web page. Code that implements Ajax in different browsers can be lengthy and tedious, but thanks to the help of jquery (and other libraries), we can implement client-server communication in a very easy and elegant way.

We can use the jquery cross-browser interface $.ajax to easily retrieve data, but it doesn't show what's going on behind the scenes. Like what:

var Data;$.ajax ({    "SOME/URL/1",    function(data) {        // but , this will!         console.log (data);}    }) // Oops, this won ' t work ... Console.log (data);

The easier mistake is to use data immediately after calling $.ajax, but this is actually the case:

Truefunction(data) {    if (xmlhttp.readystate = = = 4 ) {        Console.log (data);     null );

The underlying XMLHttpRequest object initiates the request and sets the callback function to handle the XHR Readystatechnage event. Then execute the XHR send method. In the XHR run, the ReadyStateChange event is triggered when its property readystate changes, and only the callback function triggers execution when the XHR receives a response from the remote server.

Handling Asynchronous code

Asynchronous programming is easy to get caught up in what we often call "callback Hell". Because in fact almost all of the asynchronous functions in JS use callbacks, the result of successive execution of several asynchronous functions is a layer of nested callback functions and the accompanying complex code.

Many of the functions in node. js are also asynchronous.

JavaScript makes it easy to write asynchronous code. Use promises, events, or named functions to avoid "callback hell".

In-depth understanding of synchronization and Asynchrony in JavaScript programming

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.