Asynchronous Programming in JavaScript

Source: Internet
Author: User

An asynchronous for an event

Events are one of the most important features of JavaScript, and Nodejs is designed using JS, which is 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 a direct call, such as Foo (), the second is to use the event to trigger, this function is called a callback function, such as passed to the SetTimeout function and Onready property.

Event Async in 1.setTimeout functions

SetTimeout is essentially an asynchronous event that triggers the event when the delay time is reached, but some times (and most of the time) are not executed at the given delay time, see the following code first

        varStart =NewDate (); SetTimeout (function() {Console.log (' SETTIMEOUT1: ',NewDate ()-start); }, 500);  while(NewDate ()-Start < 1000) {Console.log (' In While '); } document.getElementById (' Test '). AddEventListener (' click ',function() {Console.log (' Test: ',NewDate ()-start); }, false)         for(vari=0;i<10000;i++) {Console.log (' In for '); } setTimeout (function() {Console.log (' Settimeout2: ',NewDate ()-start); },1000); /*10214 in while index.jsp (line 19th) 10000 in for index.jsp (line 25th) Settimeou t1:2263 index.jsp (line 16th) settimeout2:3239 index.jsp (line 28th) test:10006 index.jsp        (line 22nd) test:28175 index.jsp (line 22nd) test:28791 index.jsp (line 22nd) test:28966 index.jsp (line 22nd)*/

If it is normal to understand that the delay function should break the while loop after 500 milliseconds, and actually not, and I did not immediately output test when I clicked on the div during the while loop and for loop, the explanation is:

A) event queue. When the settimeout function is called, the callback function that passes in to it is added to the event queue (the event is initialized and in memory), and then the subsequent code continues to execute until no more code can run (no normal running flow, not including asynchronous content such as event functions). It will run from the event queue and pop out a suitable event.

b) JS is single-threaded, the event handler will not run before the thread is idle.

2 ordinary events are asynchronous and settimeout similar to two promise objects and deferred object 1. Promise

Promise is a solution that solves the problem of nesting too many asynchronous programming callback functions such as Ajax, especially in Nodejs, where asynchrony is ubiquitous. The implementation of different frameworks for promise is the Promise API in jquery.

The principle of promise is not spoken here, and the principles are introduced in another space.

The traditional Ajax asynchronous programming is so written (before jquery1.5):

function () {    $.get() {                $.get(function () {' JSON ');    ' json ' json ');

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

$.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 =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

Scripts fall into two main categories: blocking and non-blocking. The blocking here refers to the load blocking instead of running the block.

<!DOCTYPE HTML><HTML><Head><Scriptsrc= "Headscript"></Script><Scriptdefer src= "Deferredscript"></Script></Head><Body>    <ScriptAsync defer src= "Chatwidget"></Script>    <ScriptAsync defer src= "Asyncscript"></Script></Body></HTML>

Above this part of the code is relatively standard about the location of the script in a page, 1. The traditional unmodified headscript is a blocking script, and since the browser interprets JavaScript from top to bottom, this part of the script file will be executed in the first place. And the DOM is not rendered until the execution is complete, but the CSS inside the head tag is loaded. 2. Scripts with the defer attribute are loaded at the same time as the DOM renders, but only after the DOM has been rendered, and unfortunately not all browsers support the defer attribute, so there is the jquery (function) thing. 3. With both the Async attribute and the defer attribute, the defer overwrites async, but when there is async alone, the script loads and runs when the DOM is rendered.

2. Programmable script loading

If it is not the beginning of the introduction of JS file on the page, but through user interaction to achieve dynamic loading JS script, can be added programmatically.

There are 2 ways to get a server script from the browser, Ajax gets and executes through the Eval function, and the other is inserting <script> tags in the DOM, generally in the second way, because the browser helps us generate HTTP requests and Eval leaks scopes.

varHead = document.getElementsByTagName (' head ') [0];varScript = document.createelement (' script '); Script.src= '/js/feature.js '; head.appendchild (script);
Script.onload = function () {
Now you can invoke the function defined in the script.
}

However, some older browsers do not support Onloa events, so you can use some scripts to load libraries to implement this functionality, such as Require.js.

Asynchronous programming in JavaScript

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.