面试之 闭包 return

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

经典面试题解释

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

/**

猜你喜欢

转载自www.cnblogs.com/lctstruggle/p/9093596.html