动手实现一个 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');
文章介绍了两种在JavaScript中实现repeat方法的方式,一种是使用async/await和sleep函数,另一种是递归调用并利用setTimeout。这两种方法分别演示了如何让一个函数按指定次数和间隔重复执行。
683

被折叠的 条评论
为什么被折叠?



