JavaScript Asynchronous Programming
In-depth understanding of JavaScript events
? Scheduling of events
JavaScript Event processor does not run before thread idle
Blocking of threads
var New The timing accuracy of//SetTimeout and SetInterval is lower than expected setTimeout (function() { varnew Date (); Console.log (' time elapsed ', End-start, ' Ms 'while (new Date- Start < 1000) {};
The results showed that settimeout did not use another thread
Queue
When calling SetTimeout, a delay event is queued;
Input events work exactly the same way, when a single-machine event occurs, a click event is queued. However, clicking the event handler will not execute until all currently running code is finished.
? asynchronous function type
Two main classes: I/O functions and timing functions
asynchronous I/O functions
node. js appears to create an event-driven server framework that is above a high-level language.
The JavaScript language provides perfect non-blocking I/O.
Such as:
var ajaxrequest = new XMLRequest ();
Ajaxrequest.open (' GET ', url);
Ajaxrequest.send (NULL);
Just attach an event handler and return to the event queue
Ajaxrequest.onreadystatechange = function () {
...
}
So what developers need to do is just define a callback.
Is the console.log of WebKit asynchronous?
var a = {name: ' 1 '}; Console.log (a); = ' 2 '; Console.log (a);
To open the console results after execution:
Open the console first and then execute the results:
Reason:
Console is the object provided by the console of the browser and only works when the console is open;
Console.log does not immediately take a snapshot of the object, but only stores a reference to an object;
Asynchronous timing functions
Possible for animation or simulation;
SetTimeout and setinterval (imprecise timing tools)
Defects of the above two functions: even if the delay is set to 0, the frequency of execution in the browser is approximately 200 times/second;
Reason: The HTML specification implementation of the delay/interval minimum value of 4 milliseconds;
Scenarios requiring finer granularity of timing: requestanimationframe function
? Writing of asynchronous functions
Any function that uses an asynchronous function, from top to bottom, is asynchronous.
Characteristics of asynchronous functions: non-blocking
Non-blocking emphasizes the high speed of asynchronous functions
or asynchronous functions.
Some functions are asynchronous at some point, but not at other times;
Example: jquery's function of the same name can be used to delay a function until the DOM has finished loading;
However, if the DOM has already finished loading, there is no delay, and the $ callback will be triggered immediately;
Application.js
$ (function () {
Utils.log (' ready ');
});
Utils.js
Window.utils = {
Log:function () {
if (window.console)
Console.log.apply (console, arguments);
}
};
<script src= "Application.js" type= "Text/javascript" > </script>
<script src= "Utils.js" type= "Text/javascript" > </script>
This code works fine, but only if the browser does not load the page from the cache (which causes the DOM to load well before the script runs). If this is the case, the callback passed to $ will run before setting utils.log, resulting in an error.
Caching-type Asynchronous functions
function Runcalculation (formula, callback) {
if (formula in Calculationcache) {
Return callback (Calculationcache[formula]);
};
if (formula in Calculationcallbacks) {
Return SetTimeout (function () {
Runcalculation (formula, callback);
}, 0);
};
Mathworker.postmessage (formula);
Calculationcallbacks[formula] = callback;
}
The formula has been calculated and the result is in Calculationcache. In this case, the runcalculation is synchronous.
The formula has been sent to the worker object, but the result has not been received. In this case, runcalculation sets a delay to call itself again, repeating the process until the result is in Calculationcache.
asynchronous recursion and callback storage
Avoid asynchronous recursion and use callback storage as much as possible.
return value and callback
Never define a potential synchronization and return value, but there are functions that might be used for callbacks.
Avoid using a timer method to wait for something that will change. If the same function returns both a value and a callback, make sure that the callback is not run until after the value is returned.
? handling of asynchronous errors
Most JavaScript environments provide a useful stack trace.
Error thrown inside callback
SetTimeout (function A () { setTimeout (function B () { setTimeout ( function C () { thrownew Error (' Something terrible has happened! ' ); 0); 00);
A and B do not appear in the stack track, because these three functions are run directly from the event queue;
Similarly, the Try/catch statement block cannot catch errors thrown from an asynchronous callback;
Keep in mind that asynchronous errors originating from callbacks can only be handled inside the callback.
The Windows.onerror processor returns TRUE to block the browser's default error handling behavior.
Avoid nesting more than two layers of functions. The key is to find a way to store asynchronous results outside of the function that activates the asynchronous call, so that the callback itself does not need to be nested again.
JavaScript Asynchronous Programming (i) in-depth understanding of JavaScript events