Thinking about a JS interview question

Source: Internet
Author: User

Topic:

 for (var05; i++) {    setTimeout (function () {        console.log (new  Date, i);      + );} Console.log (new Date, i);

1, the face of this code when the results are different, the following is a typical answer:

A. 20% of people will quickly scan the code and then give the result: 0,1,2,3,4,5;
B. 30% of the people will take the code to see the line, and then give the result: 5,0,1,2,3,4;
C. 50% of the people will take the code carefully, and then give the result: 5,5,5,5,5,5;

As long as you have a correct understanding of the concepts of synchronization and asynchronous code in JS, variable scope, closure, and so on, we know that the correct answer is C, the actual output of the code is:

  2, if we agreed, with the arrows to indicate its two times between the output of 1 seconds between the time interval, and the comma indicates its two times between the output of the time interval can be ignored, the results of the actual operation of the code how to describe? There are two types of answers:

A. 60% of the people will be described as: 5, 5, 5, 5 and 5, that is, each 5 has a time interval of 1 seconds;
B. 40% of the people will be described as: 5-5,5,5,5,5, that is, the 1th 5 direct output, 1 seconds later, output 5 5;

This requires the candidate to the JS timer working mechanism is very familiar with the loop execution process, almost simultaneously set 5 timers, in general, these timers will be triggered after 1 seconds, and the output of the loop is executed immediately , it is obvious that the correct description is B.

3, cross-examine: closures

If the problem is only to examine the candidate for JS asynchronous code, variable scope of understanding, the limitations are too big, next if the expected code output to: 5-0,1,2,3,4, how to change the code? Students who are familiar with closures will soon be given the following solutions:

 for (var05; i++) {    (function (j) {        setTimeout () {            Console.log ( New Date, j);          + );    }) (i);} Console.log (new Date, i);

  It is a good idea to use Iife (Immediately invoked function expression: declaration is executed) to solve the problem of closures, but beginners may not find such code very understood, At least when I first started to think about it for a while to really understand.

Is there a more intuitive approach? The answer is yes, we just have to tamper with the loop body, so that the code responsible for the output can get the I value of each cycle. What should I do? using the parameter passing of the basic type (Primitive type) in JS is the characteristic of passing by value (pass by value), it is not difficult to retrofit the following code:

var output = function (i) {    setTimeout (function () {        console.log (new  Date, i);     );}  for (var05; i++) {    output (i); // value passing the I value past }console.log (new Date, i);

 4. Cross-examine

If you expect the output of your code to be 4---5, 3--------------------------------- How to change the code? The new requirements can be precisely described as: Code execution, immediately after the output of 0, then every 1 seconds output 1,2,3,4, after the end of the loop in about 5 seconds when the output of 5 (here is used presumably, is to avoid the end of the classmate trapped in, because JS timer trigger timing may be indeterminate)

 for (var05; i++) {     (function (j) {          setTimeout () {           Console.log ( New Date, j);            + // This modifies the timer time of the 0~4     //Add timer here, timeout set to 5 seconds Console.log (new + * I       );

  It has to be admitted that this practice, while brutal and effective, is not considered an extra-bonus option. If this requirement is abstracted as follows: After the series asynchronous operation is complete (1 asynchronous operations per loop), then do the other things, how is the code organized? Are you thinking of something smart? Yes, that's Promise.

ES6 and ES7 Solutions (follow-up).

Thinking about a JS interview question

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.