Skip to content
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(console.log, 5, 1000); #162

Open
Sunny-117 opened this issue Nov 3, 2022 · 4 comments
Open

repeat(console.log, 5, 1000); #162

Sunny-117 opened this issue Nov 3, 2022 · 4 comments

Comments

@Sunny-117
Copy link
Owner

No description provided.

@weirong111
Copy link

function repeat(fn, timer, wait) {
  return function callback(...args) {
    setTimeout(() => {
      fn(...args);
      timer--;
      if (timer > 0) callback(...args);
    }, wait);
  };
}

@MC-kanon
Copy link

MC-kanon commented Mar 8, 2023

function one(func,wait,args){
    return new Promise((resolve,reject)=>{
        setTimeout(()=>{
            func.call(this,...args)
            resolve()
        },wait)
    })
}
function repeat(func, times, wait) {
    return async function(...args){
        for (let i = 1; i <= times; i++) {
            await one(func,wait,args)
        }
    }

}
const repeatLog = repeat(console.log,5,1000)
repeatLog("hello world")

@wangjs-jacky
Copy link

方案一:基于 tapable 思想,构造异步任务串

const repeat = (cb, delay = 1000, times = 5) => {
  /* 高阶函数 */
  return (text) => {
    /* 封装为 promise */
    const asyncFn = () => {
      return new Promise((resolve) => {
        setTimeout(() => {
          cb(text);
          resolve();
        }, delay);
      })
    }

    /* 执行串:Promise.resolve().then(()=>a()).then(()=>b()) */
    new Array(times).fill(asyncFn).reduce((pre, cur) => {
      return pre.then(() => cur());
    }, Promise.resolve())
  }
}

const mockLog = repeat(console.log);

mockLog("Hello world!!")

@huxuedong
Copy link

function repeat(fn, timer, wait) {
return function callback(...args) {
setTimeout(() => {
fn.apply(this, args)
timer--
if (timer > 0) {
callback.apply(this,args)
}
}, wait)
}
}

let obj = {
repeat:repeat(a,5,1000)
}
obj.repeat(1,2,3)

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Labels
None yet
Projects
None yet
Development

No branches or pull requests

5 participants