Details JavaScript Asynchronous Programming _javascript skills

Source: Internet
Author: User

The problem with asynchronous programming is not obvious in client JavaScript, but as server-side JavaScript becomes 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 not in-depth. You need to choose a method that is appropriate to your own situation.

This article introduces the asynchronous programming in JS in detail, the details are as follows

An asynchronous about the event

Event is one of the most important features of JavaScript, Nodejs is designed using JS asynchronous. So let's talk about the event mechanism here.

In a JS file, if you want to run a function, there are 2 means, one is direct call, such as Foo (), the second is to use events to trigger, this function is also called callback functions, such as passed to the SetTimeout function and Onready properties.

Asynchronous events in the 1.setTimeout function
SetTimeout is essentially an asynchronous event that triggers the event when it is delayed, but sometimes (and most of the time) does not execute at the given delay time, look at the following code

  var start = new Date ();
  settimeout (function () {
   console.log (' settimeout1: ', New Date ()-start);
  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 (line 19th) 10000 in for
  index.jsp (line 25th)
  Settimeout1:2263
   index.jsp (line 16th)
  settimeout2:3239
  index.jsp (line 28th)
  test:10006
  index.jsp (line 22nd)
  test:28 175
  index.jsp (22nd)
  test:28791
  index.jsp (line 22nd) test:28966
  index.jsp
  (line 22nd) * *

If, as is normally understood, the delay function should interrupt the while loop after 500 milliseconds, and in fact does not, and I do not immediately output test when I click div during the while loop and the For loop, the explanation is:

A) the event queue. When the settimeout function is invoked, the callback function passed in is added to the event queue (the event is initialized and in memory), and then the following code continues until no more code can run (no normal run stream, no asynchronous content, such as event functions), The event queue pops up a suitable event to run.

B JS is single-threaded and the event handler will not run until the thread is idle.

2 common events are asynchronous and settimeout similar
Two Promise objects and deferred objects

1. Promise
Promise is a solution to the problem of asynchronous programming callback functions such as Ajax, which causes the code to obscure the solution, especially in Nodejs, where asynchrony is ubiquitous. The implementation of different frameworks for promise is a promise API in jquery.

Here does not talk about the principle of promise, about the principle in another space to introduce.

Traditional Ajax asynchronous programming is written in this way (before jquery1.5):

$.get (' url ', function () {
 $.get (' Url1 ', function () {
  $.get (' Url2 ', function () {

  }, ' json ');
 }, ' json ' );
}, ' json ';

This writing code to the development and maintenance brought great difficulties, fortunately jquery1.5 after the introduction of promise, you can write this:

 $.ajax ("example.php")
. Done (function () {alert (' Success ');})
. Fail (function () {alert (' Error ');})
. Always (function () {alert ("complete");});

Now it's obviously a lot easier to look at.

2.deferred objects

var nanowrimoing = $. Deferred ();
var wordgoal = 5000;
Nanowrimoing.progress (function (wordCount) {
var percentcomplete = Math.floor (Wordcount/wordgoal *);
$ (' #indicator '). Text (PercentComplete + '% complete ');
});
Nanowrimoing.done (function () {
$ (' #indicator '). Text (' Good job! ');

Three. Worker objects and multithreading

Four. Asynchronous script loading

1. The location of traditional scripts in the page
There are two main categories of scripting: blocking and non-blocking. Blocking here means loading the block instead of running it.

<! DOCTYPE html>
 
 

The above part of the code is more standard about the location of the script on a page, 1. One of the traditional headscript that is not decorated is a blocking script, and because the browser performs JavaScript from top to bottom, this part of the script file is executed in the first place, And the DOM is not rendered until the execution is done, but the CSS inside the head tag is loaded. 2. Scripts with defer properties are loaded at the same time as Dom rendering, but will not start until the DOM is rendered, unfortunately, not all browsers support the defer attribute, so there is the jquery (function) thing. 3. At the same time, with async properties and defer properties, defer will overwrite async, but the script will load and run when the DOM renders, when there is async alone.

2. Programmable script loading
if not at the beginning of the page in the introduction of JS files, but through user interaction to achieve dynamic loading of JS script, can be joined programmatically.

There are 2 ways for the browser to get the server script, Ajax to get and execute through the Eval function, the other is to insert the <script> tag in the DOM, usually in the second way, because the browser helps us generate the HTTP request and the Eval leaks 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 invoke the functions defined in the script
}

The above is the entire content of this article, I hope that you learn JS asynchronous programming help.

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.