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

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

WBOY
Release: 2016-05-16 16:35:53
Original
1455 people have browsed 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 …;
}

Function f returns before the function processor set by setTimeout;

Be especially careful when using asynchronous processing, especially when using closure features;

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 it actually prints 10 10s;
The problem is that when the loop completes, the function is executed and i has become 10, which is 10 used in console.log(i)!

If your purpose is to print 0...9, then you can change the way and use function parameters to save 0...9 (in fact, closures are 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);
}
Related labels:
source:php.cn
Statement of this Website
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
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template