面試之 閉包 return

https://blog.csdn.net/FE_dev/article/details/74124373面試

經典面試題解釋app

 

return 函數 ,在()以後纔會執行函數

請定義這樣一個函數

function repeat (func, times, wait) {

}

這個函數能返回一個新函數,好比這樣用

var repeatedFun = repeat(alert, 10, 5000)

調用這個 repeatedFun ("hellworld")

會alert十次 helloworld, 每次間隔5秒

解答測試

/**

 * 第一題

 * @param func

 * @param times

 * @param wait

 * @returns {repeatImpl}

 */

function repeat (func, times, wait) {

    //不用匿名函數是爲了方便調試

    function repeatImpl(){

        var handle,

            _arguments = arguments,

            i = 0;

        handle = setInterval(function(){

            i = i + 1;

            //到達指定次數取消定時器

            if(i === times){

                clearInterval(handle);

                return;

            }

            func.apply(null, _arguments);

        },wait);

    }

    return repeatImpl;

}

//測試用例

var repeatFun = repeat(alert, 4, 3000);

repeatFun("hellworld");

/**
相關文章
相關標籤/搜索