Javascript asynchronous programming _ javascript skills

Source: Internet
Author: User
This article mainly introduces javascript asynchronous programming in detail. In fact, asynchronous programming as a programming language Javascript is a very interesting topic worth discussing ., For more information, see Asynchronous programmingThe problem is not obvious in the client Javascript, but as the server-side Javascript becomes more and more widely used, a large number of asynchronous IO operations make the problem obvious. Many different methods can solve this problem. This article discusses some methods, but they are not in-depth. You need to select a method that suits your needs.

This article describes asynchronous programming in js in detail. The details are as follows:

I. Event Asynchronization

Events are one of the most important features of JavaScript. nodejs is designed asynchronously using js. So here we will talk about the event mechanism.

In a js file, if you want to run a function, there are two methods: one is to directly call the function, such as foo (), and the other is to trigger the function by using the event, this function is also called a callback function, such as the setTimeout Function and onready attribute.

1. Events in the setTimeout function are asynchronous.
SetTimeout is essentially an asynchronous event. It is triggered when the delay time is reached, but sometimes (in fact, most of the time) It is not executed according to the specified delay time, first look at the following code

Var start = new Date (); setTimeout (function () {console. log ('settimeout1: ', new Date ()-start) ;}, 500); while (new Date ()-start <1000) {console. log (in while);} document. getElementById ('test '). addEventListener ('click', function () {console. log ('test: ', new Date ()-start) ;}, false) for (var I = 0; I <10000; I ++) {console. log ('in for ');} setTimeout (function () {console. log ('settimeout2: ', new Date ()-start) ;}, 1000);/* 10214 in while index. jsp (19th rows) 10000 in for index. jsp (row 25th) settimeout1: 2263 index. jsp (row 16th) settimeout2: 3239 index. jsp (row 28th) test: 10006 index. jsp (row 22nd) test: 28175 index. jsp (row 22nd) test: 28791 index. jsp (row 22nd) test: 28966 index. jsp (22nd rows )*/

According to the normal understanding, the latency function should interrupt the while loop after 500 milliseconds, but in fact it does not, and, when I click p in the while loop and for loop, the test is not output immediately. The explanation is as follows:

A) event queue. When the setTimeout function is called, The callback function passed in is added to the event queue (the event has been initialized and is in the memory), and the subsequent code is executed, until no code can be run (no normal running stream is available, excluding asynchronous content such as event functions), a suitable event will pop from the event queue to run.

B) js is single-threaded, and the event processor will not run before the thread is idle.

2. The Asynchronization of common events is similar to that of setTimeout.
Two promise objects and deferred objects

1. promise
Promise is a solution to solve the problem of obscure code caused by too many nested callback functions in asynchronous programming such as ajax, especially in nodejs, asynchronous is everywhere. The implementation of promise in different frameworks is the promise API in jquery.

The implementation principle of promise is not discussed here. The principle is described in other sections.

The traditional asynchronous ajax programming is written in this way (before jquery1.5 ):

$.get('url', function(){ $.get('url1', function(){  $.get('url2', function(){  }, 'json'); }, 'json');}, 'json');

Writing code this poses great difficulties for development and maintenance. Fortunately, after jquery1.5 introduces promise, you can write it like this:

 $.ajax( "example.php" ).done(function() { alert("success"); }).fail(function() { alert("error"); }).always(function() { alert("complete"); });

It seems much simpler now.

2. deferred object

var nanowrimoing = $.Deferred();var wordGoal = 5000;nanowrimoing.progress(function(wordCount) {var percentComplete = Math.floor(wordCount / wordGoal * 100);$('#indicator').text(percentComplete + '% complete');});nanowrimoing.done(function(){$('#indicator').text('Good job!');});

Iii. worker objects and Multithreading

Iv. asynchronous Script Loading

1. Location of traditional scripts on the page
There are two types of scripts: blocking and non-blocking. Blocking here refers to loading blocking rather than running blocking.

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.