JS face test--use for loop to print 1-10, each number appears at the interval of about 500MS

Source: Internet
Author: User

Again to brush face questions, haha.

Requirements: Use for loop to print 1-10, each number appears at an interval of about 500ms.

Analysis: Research points-closures, block-level scopes

Mode one, the use of closures + immediately execute the function, his thoughts at that time also think so, but the results do not reflect the interval 500ms


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

After modification, the result satisfies the requirement: 1.setTimeout each time interval 500*i, guaranteed every 500ms output 2. Move immediate execution to the outer layer

/** * Using a For loop to print 1-10, each number appears at an interval of approximately 500ms * method one, using closures, note settimeout, every 500ms, so the interval between each pass is multiplied by I */for (var i=1;i<=10;i++) {    (function (i) {        setTimeout (function () {            console.log (i);        },500*i);    }) (i);}

Method two, using Let,let itself is a block-level scope

for (let i=1;i<=10;i++) {    setTimeout (function () {        console.log (i);    },500*i);}

  

JS face test--use for loop to print 1-10, each number appears at the interval of about 500MS

Related Article

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.