Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

第 2 期(2019-05-09):定时输出数字 #3

Open
wingmeng opened this issue May 9, 2019 · 5 comments
Open

第 2 期(2019-05-09):定时输出数字 #3

wingmeng opened this issue May 9, 2019 · 5 comments

Comments

@wingmeng
Copy link
Collaborator

wingmeng commented May 9, 2019

来源:经典面试题
难度:★

编写一个方法,每隔 1s 依次在控制台打印出 5, 4, 3, 2, 1


参考答案:

请参考 @liwenkang 的答案,很全面。

@Wxh16144 的答案也不错,代码很优雅。

async function display() {
  for (let i = 5; i > 0; i--) {
    let num = await new Promise(resolve => {
      setTimeout(() => {
        resolve(i)
      }, 1e3)
    });

    console.log(num)
  }
}

display();

本期优秀回答者: @liwenkang

@cnyballk
Copy link

cnyballk commented May 9, 2019

const outputNumber = () => {
  const max = 5;
  let i = max;
  while (i) {
    setTimeout(i => {
      console.log(max + 1 - i);
    },1000 * i, i--);
  }
};

@liwenkang
Copy link

liwenkang commented May 9, 2019

// 利用了 let
const printNumber = () => {
    for (let i = 5; i > 0; i--) {
        setTimeout(() => {
            console.log(i)
        }, (6 - i) * 1000)
    }
}

// 利用了闭包
const printNumber = () => {
    for (var i = 5; i > 0; i--) {
        (function (i) {
            setTimeout(() => {
                console.log(i)
            }, (6 - i) * 1000)
        })(i)
    }
}

// 利用了闭包
const printNumber = () => {
    for (var i = 5; i > 0; i--) {
        setTimeout(((i) => {
            return () => {
                console.log(i);
            }
        })(i), (6 - i) * 1000);
    }
}

@Wxh16144
Copy link

Wxh16144 commented May 9, 2019

const printNumber = number => {
    console.log(number--);
    number && setTimeout(() => printNumber(number), 1000);
};
printNumber(5);

@AMY-Y
Copy link

AMY-Y commented May 9, 2019

//setTimeout循环和条件停止循环
//参考网址:https://blog.csdn.net/qq_28256783/article/details/80097092
var a=6;
function printN(){
   if(a>1){
     a=a-1;
     console.log(a);
     setTimeout("printN()",1000)
   }
}
printN();

@wingmeng
Copy link
Collaborator Author

const printNumber = number => {
    console.log(number--);
    number && setTimeout(() => printNumber(number), 1000);
};
printNumber(5);

好优雅的代码 👍 ,不过第一个数字是直接打印出来的,根据题意,所有的数字都应该隔1s才打印

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Labels
None yet
Projects
None yet
Development

No branches or pull requests

5 participants