JS Topic set 16

Source: Internet
Author: User

1.

var value1 = 0, value2 = 0, value3 = 0;

for (var i = 1; I <= 3; i++) {

var i2 = i;

(function () {

var i3 = i;

SetTimeout (function () {

Value1 + = i;

value2 + = I2;

Value3 + = i3;

}, 1);

})();

}

SetTimeout (function () {

Console.log (value1, value2, value3);

}, 100);

Find results and why

You can think of settimeout as a constant push into the code in an extra controller.

For inside the closures are all aware that closures are immediate execution of the value of the closure scope should maintain the current execution of the loop values such as I should be a three-to-three closure, but the closure of the package is settimeout

The settimeout is push to the extra controller. In this case, the current wheel execution is complete, release the CPU and then traverse the controller controller push three times settimeout code begins execution

The code begins to look for the value of the variable based on the scope of the storage time.

(Model reference event loop)--settimeout how to maintain scope = = Self Research

So the value of I in the settimeout is the final value of I after cyclic execution 4

I2 Note for the time to 3 i2=3; i++; i=4, at the end of the judgment i<=3 cycle

So

I2 Final value: 3.

Value1 12

value2 9

The most disgusting value3.

Doing this in a closure.

var i3 = i;

i3 the value output to the SetTimeout and released it.

The first time the loop executes the closure

I3=1

Second i3=2 the third time i3=3;

Corresponds to the corresponding settimeout push code is equivalent to

。。。

Value3+=1;

。。。

value3+=2;

。。。

value3+=3;

JS Topic set 16

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.