Javascript setTimeout (0), closures

Source: Internet
Author: User

SetTimeout are often used to delay the running of a function, using the method of

SetTimeout (function () {

...

}, timeout);

Sometimes settimeout (function...,0) is 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 you are using asynchronous processing. Especially when using the closure feature. be particularly careful;

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

SetTimeout (function () {

Console.log (i);

}, 0);

}

For the first time to use such a way of students. It is very 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 gets run, and I has become 10,console.log (i) using 10!

Increase your aim is to print 0 ... 9, it is possible to use a function reference to save the 0....9 in a different way (actually using closures)

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.