Javascript setTimeout () requires attention when using the closure feature _ javascript tips-js tutorial

Source: Internet
Author: User
Tags javascript settimeout
This article mainly introduces the things you need to pay attention to when using the closure feature of setTimeout (0) in Javascript. If you need it, you can refer to setTimeout which is often used to delay the execution of a function. Its usage is as follows:

The Code is as follows:


SetTimeout (function (){
...
}, Timeout );

Sometimes setTimeout (function ..., 0); for example:

The Code is as follows:


Function f (){
... // Get ready
SetTimeout (function (){
.... // Do something
}, 0 );

Return ...;
}

Function f returns the result before the function processor set by setTimeout;

Be especially careful when using asynchronous processing, especially the closure feature;

For example:

The Code is as follows:


For (var I = 0; I <10; I ++ ){
SetTimeout (function (){
Console. log (I );
}, 0 );
}

For those who use this method for the first time, they may think that the program will print 0... 9. You can print 10 10 results;
The problem is that when the loop is completed, the function is executed, and I has changed to 10, and 10 is used in console. log (I!

Add to you to print 0... 9, you can use the function parameter to save 0 .... 9 (actually, the closure is used ):

The Code is as follows:


For (var I = 0; I <10; 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.