fe-learning
fe-learning copied to clipboard
实现一个repeat函数
实现一个repeat函数
题目
实现一个repeat函数,每次间隔时间调用被包裹的函数,重复指定的次数
function repeat (func, times, wait) {
// ...
}
// 调用
const repeatFunc = repeat(console.log, 4, 500)
repeatFunc('hello~')
// 输出
// hello~ // * 4 by interval 500ms
实现
- 延长setTimeout的时间
function repeat (func, times, wait) {
if (typeof func !== 'function') throw Error('The first param for repeat is not a function!')
return (...args) => {
for (let i = 0; i < times; i++) {
setTimeout(() => {
console.log(new Date())
func.apply(null, args)
}, (i + 1) * wait)
}
}
}
- 借助Promise实现一个sleep函数
function sleep (wait) {
return new Promise((resolve, reject) => {
setTimeout(() => {
resolve(window.performance.now())
}, wait)
})
}
function repeat (func, times, wait) {
if (typeof func !== 'function') throw Error('The first param for repeat is not a function!')
return async (...args) => {
for (let i = 0; i < times; i++) {
console.log(await sleep(wait))
func.apply(null, args)
}
}
}
以上点了一些思路,抛砖引玉,仅供参考。
- 使用setInterval
function repeat(func, times, wait){
return function(arg){
var count = 1;
var intervalId = setInterval(function(){
func(arg);
count === times ? clearInterval(intervalId) : count++;
}, wait);
}
}
递归
function repeat (func, times, wait) {
let cur = 0;
return function (...args) {
const run = () => {
if (cur < times) {
cur++;
setTimeout(() => {
func.call(this, ...args)
run()
}, wait)
}
}
run();
}
}
为什么不是 func.call(this, ...args)? 而是 func.call(null, ...args)?
为什么不是 func.call(
this, ...args)? 而是 func.call(null, ...args)?
用了箭头函数,this不会丢失了,写null就可以了