For Loop + setTimeout combined with some examples (front-end interview questions), settimeout front-end

Source: Internet
Author: User

For Loop + setTimeout combined with some examples (front-end interview questions), settimeout front-end

I. background

I recently reviewed the old book "node. js Development Guide" and encountered a typical example of for loop + setTimeout. So I reorganized my ideas and recorded them.

2. execution mechanism of setTimeout and setInterval

In daily coding, you will find that it is often inaccurate to set the delay time for setTimeout and setInterval, or simply setTimeout (function () {xxx}, 0) it is not immediately executed (especially when time-consuming code is in the front). This is because js is single-threaded and there is an event queue mechanism. The callback of setTimeout and setInterval will be inserted into the event queue by the delay time, queued for execution.

SetTimeout: After the delay of delay is milliseconds, the callback function is directly added to the event queue.

SetInterval: After the delay of delay is milliseconds, first check whether there is a callback function in the event queue that has not been executed (setInterval callback function). If yes, do not add callback functions to the event queue.

See the following example:

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

Result: five values are output at the same time after one second.

Because the for loop is executed first (synchronization takes precedence over asynchronous over callback), all the five setTimeout Callbacks are inserted into the event queue and then executed together in 1 second.

Iii. Text

The following is the classic code:

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

Result: 5 5 5 5

Why is it not 1 2 3 4 5? The problem lies in the scope.

Because the console. log (I); of setTimeout is defined by var, it is a function-level scope. It does not belong to the for loop body or global. When the for loop ends, I is equal to 5. At this time, execute the five callback functions of setTimeout (refer to the above description of the event mechanism), in which the console. log (I); I goes up to find the scope. Only I under global can be found, that is, 5. Therefore, the output is 5.

Solution: manually create a scope for console. log (I); and save the value of I.

Solution 1

For (var I = 0; I <5; I ++) {(function (I) {// immediately execute the setTimeout (function () {console. log (I) ;}, 1000) ;}( I );}

The immediate execution of the function is used here. In this way, I in console. log (I); is saved in the scope of the immediate execution function generated in each loop.

Solution 2

For (let I = 0; I <5; I ++) {// let instead of var setTimeout (function () {console. log (I) ;}, 1000 );}

Let is the scope of the code block, so every for loop, console. log (I); is referenced to I under the scope of the for code block. Because this is referenced, after the for loop ends, these scopes will not be released before setTimeout is executed.

Iv. Supplement

When writing the sample code, a syntax point is found:

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

Error:

TypeError: "callback" argument must be a functionat setTimeout (timers.js:421:11)……

Baidu: setTimeout does not support parameter-passing functions. You can use an anonymous function to wrap it. See the following code:

Function a (I) {console. log (I) ;}for (var I = 0; I <5; I ++) {setTimeout (function () {// wrap a (I) ;}, 1000) with an anonymous function );}

Summary

The above section describes the for loop + setTimeout examples (front-end interview questions). I hope this will help you. If you have any questions, please leave a message, the editor will reply to you in a timely manner. Thank you very much for your support for the help House website!

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.