Javascript asynchronous programming and javascript asynchronous programming

Source: Internet
Author: User

Javascript asynchronous programming and javascript asynchronous programming

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 div 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.

<!DOCTYPE html>

The above code is relatively standard about the location of the script on a page, 1. the traditional headScript without any modification is a blocking script. Because the browser interprets and executes JavaScript from top to bottom, this part of the script file will be executed at the beginning, the DOM will not be rendered before execution, but the css in the head label will be loaded. 2. scripts with the defer attribute will be loaded at the same time as DOM rendering, but will be executed only after DOM rendering is complete. Unfortunately, not all browsers support the defer attribute, that's why jquery (function) exists. 3. When both the async attribute and the defer attribute are included, defer will overwrite async, but when there is async separately, the script will load and run during DOM rendering.

2. Programmable Script Loading
If you do not introduce js files on the page from the very beginning, but dynamically load js scripts through user interaction, you can add them through programming.

The browser has two methods to obtain the server script. ajax gets the script and runs it through the eval function. The other method is to insert the <script> tag in the DOM. The second method is generally used, because browsers help us generate HTTP requests and eval will expose the scope.

Var head = document. getElementsByTagName ('head') [0]; var script = document. createElement ('script'); script. src = '/js/feature. js'; head. appendChild (script); script. onload = function () {// now you can call the function defined in the script}

The above is all of the content in this article, hoping to help you learn js asynchronous programming.

Articles you may be interested in:
  • Javascript asynchronous programming
  • JavaScript asynchronous programming: a specific method of asynchronous data collection
  • Four Methods of javascript asynchronous programming
  • Six features of the Promise mode in JavaScript asynchronous programming
  • Detailed introduction to the Javascript asynchronous programming model Promise Mode
  • Detailed introduction to asynchronous programming specification Promises/A in Javascript
  • Four methods for implementing asynchronous programming in JavaScript
  • Asynchronous programming practices of when. js under node. js
  • Nodejs asynchronous programming
  • Introduction to Node. js asynchronous programming Callback (1)

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.