js-challenges icon indicating copy to clipboard operation
js-challenges copied to clipboard

repeat(console.log, 5, 1000);

Open Sunny-117 opened this issue 2 years ago • 4 comments

Sunny-117 avatar Nov 03 '22 08:11 Sunny-117

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

weirong111 avatar Nov 06 '22 09:11 weirong111

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")

MC-kanon avatar Mar 08 '23 02:03 MC-kanon

方案一:基于 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!!")

wangjs-jacky avatar Oct 17 '23 14:10 wangjs-jacky

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)

huxuedong avatar Jan 16 '24 07:01 huxuedong