setTimeout面试题

一.考察闭包

// 输出全为10

for(var i=0;i<10;i++){

   setTimeout(function(){

       console.log(i);

   },50);

}

 

答1:使用闭包

for(var i=0;i<10;i++){

    (function(i){

        setTimeout(function(){

        console.log(i);

        },50);

    })(i);

}

答2.使用ES6块级作用域

for (let i = 0; i < 5; i++) {

setTimeout(() => {

console.log(i);

}, 1000);

}

 

二、考察异步

问下面console.log的顺序

var arr = [1000,2000,1000];

for (let j = 0; j < arr.length; j++) {

setTimeout(() => {

console.log(j);

}, arr[j]);

}

答:

0,2,1

 

问:如何使上面console.log按顺序执行?

答:使用递归

​
var i = 0; 
function isfun() {  
     //your code here 把逻辑写在settimeout里,用递归的方式
    //-----
    console.log(i);
    let docs = [1000, 2000, 1000];
    (++i < 3) && setTimeout("isfun()", docs[i - 1]);    
    
    /*或者通俗点这样写
    i++;
    if(i<30){
        setTimeout("isfun()", 3000);
    }
    */
}

​

 

改进:减少全局变量

function isfun2(k = 0) {   
    //your code here 把逻辑写在settimeout里,用递归的方式
    //-----
    console.log(k);
    let docs = [1000, 2000, 1000];
    (++k < 3) && setTimeout(() => {
        isfun2(k)
    }, docs[i - 1]);

    /*或者通俗点这样写
    i++;
    if(i<30){
        setTimeout("isfun()", 3000);
    }
    */
}

三、编程题

题目:实现一个类,使每隔指定的秒数执行对应的console.log

new Queue()

.task(() => {

console.log(1)

}, 1000)

.task(() => {

console.log(2)

}, 2000)

.task(() => {

console.log(3)

}, 1000)

.run()

答:

class Queue {
    args = [];
    _self = this;
    task(fn,time) {
        this.args.push([fn,time]);
        return this._self;
    };
    run(k = 0) { 
        let that = this;
        that.args[k][0]();
        (++k < that.args.length) && setTimeout(() => {
            that.run(k)
        }, that.args[k][1]);

    }

}

 

  • 1
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值