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