Skip to main content

实现一个repeat方法

一、题意

使用JS实现一个repeat方法

function repeat (func, times, wait) {
//...
}
const repeatFunc = repeat(alert, 4, 3000);

调用这个 repeatedFunc("hellworld"),会alert4次 helloworld, 每次间隔3秒

const repeatFunc = repeat(alert, 4, 3000)
repeatedFunc("hellworld")

二、解法

tip

解答此题的关键,在于使用await语法,结合event loop的机制,对执行语句进行阻塞。
如果单单靠setTimeout,是无法做到每次间隔3秒的要求。

function repeat (func, times, wait) {
return async (word) => {
for(let i = 0; i < times; i++){
await sleep(wait);
func(word);
}
}
}

function sleep(time){
return new Promise(resolve => {
setTimeout(() => {
resolve();
}, time);
});
}