码迷,mamicode.com
首页 > 其他好文 > 详细

面试之 闭包 return

时间:2018-05-26 18:00:30      阅读:179      评论:0      收藏:0      [点我收藏+]

标签:==   span   col   nts   imp   调试   app   试题   次数   

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

/**

 

面试之 闭包 return

标签:==   span   col   nts   imp   调试   app   试题   次数   

原文地址:https://www.cnblogs.com/lctstruggle/p/9093596.html

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!