Javascript setTimeout (0), closures

Source: Internet
Author: User

SetTimeout is often used to defer execution of a function, using the

SetTimeout (function () {

...

}, timeout);

SetTimeout (function...,0) is sometimes used for asynchronous processing, for example

function f () {

...//Get ready

SetTimeout (function () {

....//Do something

}, 0);

return ...;

}

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

When using asynchronous processing, especially when using the closure feature, be especially cautious;

for (var i = 0; i < i++) {

SetTimeout (function () {

Console.log (i);

}, 0);

}

For students who first use this method, it is likely that the program will print 0 ... 9, the results are indeed printed 10 10;

The problem is that when the loop is complete, the function is executed, and I has become 10,console.log (i) using 10!

Join your goal is to print 0 ... 9, then you can use the function parameter to save the 0....9 in a different way (actually using the closure)

for (var i = 0; i < i++) {

SetTimeout ((function (i){

return function () {

Console.log (i);

}

}) (i), 0);

}

Javascript setTimeout (0), closures

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.