动手实现一个 repeat 方法
function repeat(func, times, wait) {
// TODO
}
const repeatFunc = repeat(alert, 4, 3000);
// 调用这个 repeatFunc ("hellworld"),会alert4次 helloworld, 每次间隔3秒
方法一:
async function sleep(fn, wait, args) {
return new Promise((resolve) => {
setTimeout(() => {
fn.apply(this, args)
resolve()
}, wait)
})
}
function repeat(func, times, wait) {
return async function() {
for (let i = 0; i < times; i++) {
await sleep(func, wait, arguments)
}
}
}
var repeatFunc = repeat(alert, 4, 3000);
repeatFunc('helloworld')
方法二:
function repeat(func, times, wait) {
return function(...args) {
const _this = this;
function recursiveCall(count) {
if (count > 0) {
setTimeout(() => {
func.apply(_this, args);
recursiveCall(count - 1);
}, wait);
}
}
recursiveCall(times);
};
}
var repeatFunc = repeat(alert, 4, 3000);
repeatFunc('helloworld');