When using the closure feature of setTimeout () in Javascript, you need to pay attention to the problem.

Source: Internet
Author: User

When using the closure feature of setTimeout () in Javascript, you need to pay attention to the problem.

SetTimeout is often used to delay the execution of a function. Its usage is:

Copy codeThe Code is as follows:
SetTimeout (function (){
...
}, Timeout );

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

Copy codeThe 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:

Copy codeThe 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 ):

Copy codeThe Code is as follows:
For (var I = 0; I <10; I ++ ){
SetTimeout (function (I ){
Return function (){
Console. log (I );
}
}) (I), 0 );
}


Three questions about JavaScript Closure

1. because the execution is asynchronous, when it is executed, it gets the value of variable I, then I = 10. so every time it is 10. after setTimeout, the execution will be delayed by 1 second. In 1 second, the for loop is certainly finished, so I = 10. to register asynchronous execution, only the variable symbol name is given when closure is created, and the value of this variable is obtained during execution. In order to copy the current value, we need to create an object to copy this value.
<Script>
Var Handler = function (no ){
Var _ no = no;
This. run = function (){
Alert (_ no );
};
};

For (var I = 0; I <10; I ++ ){
SetTimeout (new Handler (I). run, 1000 );
}
</Script>

2. Because the for loop redefines the function a three times, you can only use the most defined function.
3. Question 3 refer to question 2. In the same principle, the last definition can only be used for three times.

JavaScript Closure

Closure is the syntax feature of ECMAScript, that is, defining a function within a function. Internal functions can access the scope of their external functions. JavaScript also implements this feature. The term closure is indeed obscure, but the implementation of closure is actually very simple. As long as you understand the scope rules of JS, you will naturally understand the closure. For example,
Function outer (name) {// external function var msg = "hello"; function inner () {// internal function alert (msg + "" + name );} return inner (); // returns the internal function} var clos = outer ("Wang"); clos (); this Code uses a closure, the warning "hello Wang" is displayed when the code is executed ".
First, explain the scope ). When you run a function, the context and scope of the function are created. The scope is the variables in the current environment. The most peripheral environment in JS is the window object, that is, the environment where the global scope is located. When executed to the next stage, the next stage will take the initiative to include the Scope of the previous level, and finally form a Scope chain of the first-level Association (The [Scope] attribute of the object points to the Scope chain ). When the next stage is generated, the previous stage will become inactive, but will not be destroyed automatically and stored in a "stack" structure. This ensures the continuity of the scope chain, it can also be activated again when the environment is rolled back. The current environment can access all the variables in the current scope chain. For example, the inner () function in the code above can access the msg and name variables in the outer () function. With this scope chain, closures allow internal functions to access the variables of external functions. On the other hand, they can also suppress the destruction of external function environments so that their variables are always stored in the memory, and then destroy the device when it is not needed. As for the closure application, there are actually some tips. Below are some examples.
Bind events cyclically to make index I valid during the loop Process
Var elems = document. getElementsByTagName ('lil'); for (var I = 0; I <elems. length; I ++) {elems [I]. onclick = function (I) {return (function () {// closure alert (I) ;})} (I); // The anonymous function is used here, in practical applications, it is more common} to construct a function name reference without parameters, because the closure function generally does not have Parameters
// Use the previous outer function example var clos = outer ("Wang"); setTimeout (clos, 100); Module encapsulation. For example, there is similar code in jQuery, ensure that internal variables do not affect global variables
Function ($) {// jQuery internal Implementation}) (jQuery); // an automatically executed anonymous function is used here, that is, an anonymous function is defined and executed immediately. It seems to have nothing to do with the closure, but it turns out to be the same.
However, it is best to use less closures. Previously, closures will keep variables in the memory. Improper use will increase the memory overhead and even lead to the risk of Memory leakage. Of course, you can still use a similar
// Use the previous outer function example clos = null; the Code releases the memory occupied by the variable and helps the GC mechanism to recycle it.


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.