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]);

    }

}

 

發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章