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

高洛峰
Release: 2017-02-08 16:06:39
Original
964 people have browsed it

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 after login

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

Copy codeThe code is as follows:

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

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 codeThe code is as follows:

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

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 codeThe code is as follows:

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

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!

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
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template
About us Disclaimer Sitemap
php.cn:Public welfare online PHP training,Help PHP learners grow quickly!