Confusion in the generation of asynchronous and closed packets in JavaScript

Source: Internet
Author: User

Here I'm not going to talk about what is asynchronous, what is closures, these content in the blog park has been written enough, but these content appears to be more, does not mean that all beginners are already holding, so I still intend to use a more common example to analyze, Perhaps the students who are confused about the problem have a sense of epiphany. I was in the previous blog, "From a question analysis closure > has analyzed what is closed, but that example application of the scene is more complex, not suitable for beginners to understand, here I give a more common example."

If there is a need: Click on each item in the menu, display the content clicked, the corresponding content page is as follows:

<!DOCTYPE HTML><HTML><Head><title>Test</title><Metaname= "Viewport"content= "Width=device-width, initial-scale=1"><Metahttp-equiv= "Content-type"content= "text/html; charset=utf-8" /> </Head><Body> <ul>     <Li>List 0</Li>     <Li>List 1</Li>     <Li>List 2</Li>     <Li>List 3</Li>     <Li>List 4</Li> </ul>  <Scripttype= "Text/javascript"> </Script></Body></HTML>

Let me start with a problematic JS code, which is implemented like this:

  var items =  document.queryselectorall (' li ');   var len = items.length;    for (var i =0;i<len;i++) {      function() {          alert (' list ' +i)      }  }

At this time, I found that every Li tag has a click event, it seems to run very well, but when I have a few more, found that the problem is coming, no matter which Li tag I order, pop up is List 5. What is the reason?

Enthusiastic netizens immediately replied, because the pop-up I is the value after the loop. That's the answer, and the question comes again:

1: Since the pop-up is the value after the loop, why is every Li label on the state of events?

2: It is not only the 5th LI element can state events, and the page does not exist at all this element, it is not a click, it should be error?

It is not clear that the answer to this question has not been explained clearly, but added more questions. The root cause of the problem here is that there is an asynchronous process. The Loop code is synchronous, and the click Operation is asynchronous.

I use a game to demonstrate this process:

On the playground stood 4 children (corresponding to 4 Li elements), the teacher told them all the rules of the game (corresponding loop), the rule is this: The teacher will hold a small blackboard, and then point your name, you tell the teacher on the blackboard what the word is written. (corresponding to the function set by the onclick). The game began, the teacher wrote on the Blackboard 1, feel bad, changed to 2, then changed to 3, and finally changed to 4. The children watched the teacher change to change, waited for a long time to start the game.

But no matter what little friend, he answered "4". Because all they see is the number that the teacher wrote last.

Now let's go back and look at the code just now.

 varItems = Document.queryselectorall (' li '); varLen =items.length;  for(varI =0;i<len;i++){     //when I=0, that is, items[0] corresponds to the element, which is determined.     //Items[i] A value operation is performed hereItems[i].onclick =function(){          //and I have to wait until this function is running to determine how much         //when the function is running, it must have happened after the loop. Because the speed of the click is obviously more than the speed of the CPU operation.Alert (' list ' +i)}}

The game just now is obviously not what the teacher expected. This time she replaced the small blackboard with a small piece of paper that was written, passing the pieces of paper to each of them when they said the rules. In this way, each child has a number in his hand that belongs to him. When the teacher gave the name, they all reported the numbers on their paper. The teacher was satisfied with his ideas.

So, how do we make a small piece of paper in advance and pass it on to each LI element?

Method One:

Make a mark on Li and take the value on this mark when you point.

  var items =  document.queryselectorall (' li ');   var len = items.length;    for (var i =0;i<len;i++) {      items[i].setattribute (' i ', i);       function () {          this. getattribute ("I");          Alert (' list ' +i)      }  }

Method Two:

Using the characteristics of closures

  var items =  document.queryselectorall (' li ');   var len = items.length;    for (var i =0;i<len;i++) {      = (function() {          var t =  i;           return function () {              alert (' list ' +t)}}       )  }

Method Three: Using closures more difficult to understand, we change a way

  var items =  document.queryselectorall (' li ');   var len = items.length;    for (var i =0;i<len;i++) {             function(t) {              alert (' list ' +t)      }.bind (this, i)  }

To summarize:

Although the above uses three forms of small pieces of paper for the reference, but the purpose is to ensure that after the cycle, each Li's callback function parameters can be determined. This small piece of paper is a useful technique for solving asynchronous problems.

On the question of asynchrony, there are many, because of the time relationship, it is no longer listed, interested students can @ me, study together.

If you think this article is helpful to you, please click "Recommend", would you like to study with me? Then "pay attention" to me!

Confusion in the generation of asynchronous and closed packets in JavaScript

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.