前端面试题 每隔一段时间执行一个函数 执行次数一定 setInterval

setInterval的应用

题目要求是实现一个function repeat (func, times, wait) { }函数,每隔wait毫秒执行func函数times次,调用过程如下:
const repeatFunc = repeat(alert, 4, 3000)
repeatFunc(“hellworld”);

解答:
通过调用方式repeatFunc(“hellworld”);可以知道这个repeatFunc函数是可以传参的,说明repeat的返回值是一个函数。

function repeat (func, times, wait) {
		return function(content){
		
		}
 }

每隔wait毫秒执行func函数times次:可以通过setInterval,内含一个计数变量,当达到times时,clearInterval。(注意不能用for+setTimeout,因为for是同步的,导致setTimeout全都放到队列里,没有了时间间隔)
完整代码:

function repeat (func, times, wait) { 
           return function(content){
            var count = 0;
            var interval = setInterval(function(){
                count += 1;
                func(content);
                if(count === times){    
                    clearInterval(interval);    
                }
            }, wait);
	}
}  
const repeatFunc = repeat(alert, 4, 3000)
repeatFunc("hellworld");
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值