SetTimeout in js

Source: Internet
Author: User
Tags setinterval

In the work, you need to write a latency pop-up window and think of setTimeout in for. The result shows that there is no latency as required.

So I wrote a simple test:

For (var k = 1; k <= 9; k ++ ){
SetTimeout (aa (k), 1000 );
Console. log (k );
}
 
Function aa (k ){
Console. log ('K: '+ k );
}

It was found that there was no waiting at all. On the Internet, it was said that setTimeout was asynchronous. That is to say, the for operation is complete and the setTimeout operation is still in progress. However, this shows that the method in setTimeout is executed, but there is no latency.
Change to setTimeout (aa (k), 1000 * k); this problem still exists.

1. Use setInterval () to simulate:

Var d = 1;
Var timer = setInterval (function (){
Console. log (d );
D ++;
 
If (d> 9) clearInterval (timer );
},1000 );

2. Closure implementation:

For (var j = 1; j <= 9; j ++ ){
(Function (j ){
SetTimeout (function timer (){
Console. log (j );
}, 1000 * j );
}) (J );
}

3. Define block variables for implementation:

For (let I = 1; I <= 9; I ++ ){
SetTimeout (function timer (){
Console. log (I );
}, 1000 * I );
}

For the next reference.

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.