JavaScript settimeout () issues to be aware of when using closure features

Source: Internet
Author: User
Tags closure javascript settimeout

SetTimeout is often used to delay execution of a function:

The code is as follows:
settimeout (function () {
...
}, timeout);

Sometimes the settimeout (function...,0) is used for asynchronous processing, for example:

The code is as follows:
function f () {
..//Get Ready
settimeout (function () {
.../Do Something
}, 0);

return ...;
}

function f is returned before the function processor set by settimeout.

Be especially careful when using asynchronous processing, especially when using closure features;

For example:

The code is as follows:
for (var i = 0; i < i++) {
settimeout (function () {
Console.log (i);
}, 0);
}

For the first time to use this method of students, it is likely that the program will print 0 ... 9, the result is actually printing 10 10;
The problem is that when the loop completes, the function is executed, and I has become 10,console.log (i) using 10!

Add your purpose is to print 0 ... 9, you can use the function parameter to save the 0....9 (in fact, the closure) in a different way:

The code is as follows:
for (var i = 0; i < i++) {
SetTimeout ((function (i) {
return function () {
Console.log (i);
}
}) (i), 0);
}

Related Article

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.