-
Notifications
You must be signed in to change notification settings - Fork 896
New issue
Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.
By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.
Already on GitHub? Sign in to your account
动手实现一个 repeat 方法 #148
Labels
Comments
|
function repeat(func, times, wait) {
function sleep(fn, wait, args) {
return new Promise((resolve, reject) => {
setTimeout(() => {
try {
const res = typeof fn === 'function' && fn.apply(this, args);
resolve(res);
} catch (error) {
reject(error);
}
}, wait);
});
}
// TODO
return async function (...args) {
const promises = new Array(times).fill(sleep);
for (const p of promises) {
await p(func, wait, args);
}
}
}
const repeatFunc = repeat(console.log, 4, 3000);
repeatFunc ("hellworld"); |
function repeat(func, times, wait = 1000) {
// TODO
return async function (...args) {
function delay(fn, wait) {
return new Promise((resolve, reject) => {
setTimeout(() => {
try {
const res = typeof fn === 'function' && fn.apply(this, args);
resolve(res);
} catch (error) {
reject(error);
}
}, wait);
});
}
while (times > 0) {
await delay(func, wait);
times--;
}
typeof cb === 'function' && cb.apply(this, args);
}
}
const repeatFunc = repeat(console.log, 4, 3000);
repeatFunc('hellworld'); |
function repeat(func, times, wait) {
return function (...args) {
let that = this
let count = 0
let result
let handler = setInterval(() => {
if (count >= times) {
clearInterval(handler)
return
}
result = func.apply(that, args)
count++
}, wait);
return result
}
} |
const repeat = (cb, times, interval) => (value) => {
let count = 0
const execution = () => {
setTimeout(() => {
count++
cb(value)
if (count < times) execution()
}, interval)
}
execution()
}
repeat(console.log, 5, 200)("hi") |
|
|
function repeat(func, times, wait) {
let c = 0
let timer = null
return function repeated(...args) {
func.call(this, ...args)
c++
timer = setInterval(() => {
func.call(this, ...args)
c++
if (c === times) {
clearInterval(timer)
timer = null
}
}, wait)
}
} |
function sleep(time) {
return new Promise(resolve => {
setTimeout(() => {
resolve();
}, time);
});
}
function repeat(func, times, wait) {
return async function wrappedFunction(...args) {
for (let index = 0; index < times; index++) {
await sleep(wait);
func.call(this, ...args);
}
};
}
const repeatFunc = repeat(console.log, 4, 3000);
repeatFunc("hellworld"); |
function repeat(func, times, wait) {
let timer = null;
return function fn(...args){
timer = setTimeout(() => {
func.apply(this, args);
times--;
if(times > 0){
fn(...args);
}
}, wait)
}
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
The text was updated successfully, but these errors were encountered: