What is async?
JS is a single-threaded execution environment, a certain time can only perform a task, unable to perform multiple tasks, in order to execute the code, there is a JavaScript task queue. Based on this concept, JS performs tasks in two different modes: synchronous and asynchronous.
"synchronous mode" means that the latter task must wait for the previous task to complete before it is executed, and the previous task will block the subsequent program when it is loaded;asynchronous mode does not necessarily perform the task sequentially, so it does not block the running of the program.
// synchronization Mode console.log (+);alert (console.log); // Print Result: 100,200, (Wait for the alert box to click OK)
// Asynchronous Mode Console.log (+),setTimeout (function () { console.log ();}, (Console.log); // printing results: 100,300, (after one second)
Execution process: Execute Console.log (100) First, and then execute settimeout, because it is an asynchronous function, so the function is staged to put aside, not immediately execute, and then execute Console.log (300); After the program has finished executing, the queue is idle. View the staged settimeout, execute the function directly if there is no wait time, and then wait for a certain amount of time after the function is executed.
(If there are multiple wait times different settimeout, first execution wait time is short)
Front-end use of asynchronous scenarios
When does it need to be asynchronous? There may be cases where the wait is required to continue executing the code. For example, the wait does not block the operation of the program as alert in the above example. Therefore, you need to wait for the case to be asynchronous.
1, Scheduled tasks: Settimeout,setinterval. examples are as above;
2, Network request: Ajax request, dynamic load;
// ajax Request example Console.log ("Start"); $.get ( "./data.json", function // print Result: Start,end, (after request to JSON data) data
// img Load Example console.log ("Start"); var img = document.createelement ("img"function () { console.log ("onload" = "/xx.jpg"; Console.log ("End"); // Print Result: Start,end, (img image loading complete) onload
3. Event binding (click multiple times to execute)
// The Event binding example Console.log ("Start");d Ocument.getelementbyid ("btn"). AddEventListener (' click ', function () { console.log ("clicked");}) Console.log ("End"); // Print Result: Start,end, (after clicking the Click event) clicked
Understanding JS Async and Single-threaded