Home  >  Article  >  Web Front-end  >  Issues you need to pay attention to when using the closure feature of Javascript's setTimeout()

Issues you need to pay attention to when using the closure feature of Javascript's setTimeout()

高洛峰
高洛峰Original
2017-02-08 16:06:39977browse

This article mainly introduces the issues that need to be paid attention to when using the closure feature of Javascript's setTimeout(0). Friends in need can refer to it

setTimeout is often used to delay the execution of a certain function. The usage is: :

##Copy code The code is as follows:

setTimeout(function(){
…
}, timeout);

Sometimes setTimeout(function...,0) is used for asynchronous processing; for example:

Copy code The code is as follows:

function f(){
… // get ready
setTimeout(function(){
…. // do something
}, 0);
  
return …;
}

Before the function processor set by setTimeout, function f returns;

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

For example:

Copy code The code is as follows:

for(var i = 0 ; i < 10; i++){
setTimeout(function(){
console.log(i);
}, 0);
}

For students who are using this method for the first time, they may think that the program will print 0...9, but the result will indeed print 10 10s;

The problem is that when the loop is completed, the function is executed , and i has become 10, the value used in console.log(i) is 10!

Your purpose is to print 0...9, then you can change the way and use function parameters to save 0...9 (in fact, closure is also used):

Copy code The code is as follows:

for(var i = 0 ; i < 10; i++){
setTimeout((function(i){
return function(){
console.log(i);
}
})(i), 0);
}

For more issues that need to be paid attention to when using the closure feature of Javascript's setTimeout(), please pay attention to the PHP Chinese website for related articles!

Statement:
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn