FE-Interview
FE-Interview copied to clipboard
Day155:动手实现一个 repeat 方法
function repeat(func, times, wait) {
// TODO
}
const repeatFunc = repeat(alert, 4, 3000);
// 调用这个 repeatFunc ("hellworld"),会alert4次 helloworld, 每次间隔3秒
每日一题会在下午四点在交流群集中讨论,五点小程序中更新答案 二维码加载失败可点击 小程序二维码
扫描下方二维码,收藏关注,及时获取答案以及详细解析,同时可解锁800+道前端面试题。
function repeat(func, times, wait) {
if (times <= 0) return
let timer = null
let count = 0
return function inner() {
const self = this
timer = setTimeout(() => {
if (count === times) {
clearTimeout(timer)
return
}
count++
func.apply(self, arguments)
inner.apply(self, arguments)
}, wait)
}
}
function repeat(func, times, wait) {
if (times <= 0) return
let timer = null
let count = 0
return function inner() {
const self = this
timer = setTimeout(() => {
if (count === times) {
clearTimeout(timer)
return
}
count++
func.apply(self, arguments)
inner.apply(self, arguments)
}, wait)
}
}
const repeatFunc = repeat(alert, 4, 3000)
repeatFunc( 'hellworld ')
const repeat = (func, times, wait) => async (...args) => {
try {
let timer;
for (let i = 0; i < times; i++) {
await new Promise((resolve) => {
func(...args);
timer = setTimeout(() => {
resolve();
}, wait);
});
}
clearTimeout(timer);
} catch (e) {
console.error(e);
}
}
const repeatFunc = repeat(alert, 4, 3000);
repeatFunc('hello world');
// 1.
function repeat(func, times, wait) {
return function(...args) {
for (let i = 0;i < times;i++) {
setTimeout(() => {
func(...args);
}, wait * i);
}
}
}
const repeatFunc = repeat(alert, 4, 3000);
// 2
function repeat(func, times, wait) {
return function(...args) {
new Array(times).fill().reduce((pre, cur, index) => {
return pre.then(res => {
return new Promise(r => {
func(...args);
setTimeout(() => {
r();
}, wait);
})
})
}, Promise.resolve())
}
}
const repeatFunc = repeat(alert, 4, 3000);
// 3
const repeat = (func, times, wait) => async (...args) => {
try {
let timer;
for (let i = 0; i < times; i++) {
await new Promise((resolve) => {
func(...args);
timer = setTimeout(() => {
resolve();
}, wait);
});
}
clearTimeout(timer);
} catch (e) {
console.error(e);
}
}
function repeat(func, times, wait) {
let num =1
return new Proxy(func, {
apply(target,tha,a){
setTimeout(()=>{
target(a)
num++
console.log(num,times)
if (num<=times){
repeatFunc(num)
}
}, wait)
}
})
}