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 codeThe code is as follows:
setTimeout(function(){ … }, timeout);
Copy codeThe code is as follows:
function f(){ … // get ready setTimeout(function(){ …. // do something }, 0); return …; }
Copy codeThe code is as follows:
for(var i = 0 ; i < 10; i++){ setTimeout(function(){ console.log(i); }, 0); }
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 codeThe code is as follows:
for(var i = 0 ; i < 10; i++){ setTimeout((function(i){ return function(){ console.log(i); } })(i), 0); }