Sunny-117 / js-challenges

✨✨✨ Challenge your JavaScript programming limits step by step

Home Page:https://juejin.cn/column/7244788137410560055

Geek Repo:Geek Repo

Github PK Tool:Github PK Tool

repeat(console.log, 5, 1000);

Sunny-117 opened this issue · comments

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

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

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

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)