Let's talk about the async in JS, and how asynchronous, Rookie edition

Source: Internet
Author: User
Tags script tag

Why is async required? Why Look at a piece of code.

Question 1:

for (Var i=0;i<100000;i++) {

}

Alert (' Hello world!!! ');

This code means to do 100 ... After the next implementation of alert, the problem is that seriously blocked the execution of the code behind, as for why, mainly because JS is single-threaded.

Question 2:

We usually have to solve this problem, if we need to add script code in the head, it will generally write the code in Window.onload (if the DOM is manipulated), you have not thought, why add window.onload? The reason is that when you manipulate the DOM, the HTML code browser behind the script has not yet started to load, and it is possible that the person is not born and you want to marry her. Of course not, plus window. The reason that onload is possible is that the code inside the window.onload is executed after all the documents have been loaded, which is equivalent to Asynchrony.

Question 3:

Sometimes the page doesn't need to load all the code at once, and more often we just load a piece of code as needed.

What is a single thread?

You can understand that a single thread is the execution of a piece of code, first executing the previous one, and then executing it later.

What are the asynchronous ones in JS?

I believe that this thing, almost all rotten, it is settimeout/setinterval of course, and Ajax,ajax asynchronous I believe we all know, of course, can be synchronized but no one to do so, But for settimeout and setinterval, it may be that some small partners have different understanding of the async, and here's why settimeout is asynchronous.

SetTimeout (function () {
Console.log (0);
},0)

Console.log (1);

1

0

After running this code is 1, instead of 0, some small partners are not beginning to confuse, here we give settimeout set is 0 seconds after the execution of Console.log (0), but this settimeout is very special, because it is asynchronous, Let's just leave it out here. Why print 1 and then 0, first to talk about what is asynchronous.

What is async?

For example, some restaurants you go to dinner need to book in advance, so that other people eat you can go, so in other people when you eat to do other things, and other people will notify you when they have finished, so you can go, then for the code, such as Ajax, you define a callback method, This callback method does not execute at that time, but waits for the server response to complete before executing the code.

We go back to that section of settimeout body, it works like this, when you define settimeout the moment (regardless of whether the time is 0), JS will not go directly to execute this code, but to throw it into an event queue, when all the synchronization tasks in the page is done, To execute the code inside the event queue. What is synchronization, except that asynchronous code is synchronous-_-.

How does JS achieve asynchrony?

1. Using Settimout to implement asynchronous

    

SetTimeout (function () {
Console.log (Document.getelementbytagname (' body ') [0]);
},0)

But settimeout has some small problem, that is, time is not accurate, if you want to execute this code faster, we can use a function provided by HTML5.

  

Requestanimationframe (function () {
Console.log (Document.getelementbytagname (' body ') [0]);
})

The difference between Requestanimationframe and settimeout is that Requestanimationframe is executed faster than settimeout, so many people use requestanimationframe to make animations.

  

2. Dynamically create a script tag

  

var head = document.getelementbytagname (' head ') [0];
var script = document.createelement (' script ');
SCRIPT.SRC = ' Chasing the dream son JS ';
Head.appendchild (' script ');

3. Using the Defer/async provided by script

<script src= "Xx.js" defer></script>

Defer: Executes this code when the page is loaded.

<script src= "Xx.js" async></script>

Async: Execute script code asynchronously

  

However, Async is also a disadvantage, such as the following code:

Normal code:

    

try{
throw new Error (' Hello World ');
}catch (Err) {
Console.log (ERR);
}

Error:hello World (...)

Async Code:

  

try{
Settimout (function () {
throw new Error (' Hello World ');
},0)
}catch (Err) {
Console.log (ERR);
}

Referenceerror:settimout is not defined (...)

You can see that the code inside the catch is not executed, meaning that the try cannot capture the code inside the async.

Have a private conversation with the front end of me.

Let's talk about the async in JS, and how to do it asynchronously, rookie edition

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.