fe-learning icon indicating copy to clipboard operation
fe-learning copied to clipboard

实现一个repeat函数

Open metroluffy opened this issue 5 years ago • 4 comments

实现一个repeat函数

题目

实现一个repeat函数,每次间隔时间调用被包裹的函数,重复指定的次数

function repeat (func, times, wait) {
  // ...
}
// 调用
const repeatFunc = repeat(console.log, 4, 500)
repeatFunc('hello~')
// 输出
// hello~ // * 4 by interval 500ms

实现

  1. 延长setTimeout的时间
function repeat (func, times, wait) {
  if (typeof func !== 'function') throw Error('The first param for repeat is not a function!')
  return (...args) => {
    for (let i = 0; i < times; i++) {
      setTimeout(() => {
        console.log(new Date())
        func.apply(null, args)
      }, (i + 1) * wait)
    }
  }
}
  1. 借助Promise实现一个sleep函数
function sleep (wait) {
  return new Promise((resolve, reject) => {
    setTimeout(() => {
      resolve(window.performance.now())
    }, wait)
  })
}

function repeat (func, times, wait) {
  if (typeof func !== 'function') throw Error('The first param for repeat is not a function!')
  return async (...args) => {
    for (let i = 0; i < times; i++) {
      console.log(await sleep(wait))
      func.apply(null, args)
    }
  }
}

以上点了一些思路,抛砖引玉,仅供参考。

metroluffy avatar Jun 02 '20 12:06 metroluffy

  1. 使用setInterval
function repeat(func, times, wait){
    return function(arg){
        var count = 1;
        var intervalId = setInterval(function(){
            func(arg);
            count === times ? clearInterval(intervalId) : count++;
        }, wait);
    }
}

metroluffy avatar Jun 07 '20 14:06 metroluffy

递归

function repeat (func, times, wait) {
    let cur = 0;
    return function (...args) {
      const run = () => {
        if (cur < times) {
          cur++;
          
          setTimeout(() => {
            func.call(this, ...args)
            run()
          }, wait)  
        } 
      }

      run();
    }
  }

legend80s avatar Dec 11 '23 04:12 legend80s

为什么不是 func.call(this, ...args)? 而是 func.call(null, ...args)?

legend80s avatar Dec 11 '23 04:12 legend80s

为什么不是 func.call(this, ...args)? 而是 func.call(null, ...args)?

用了箭头函数,this不会丢失了,写null就可以了

sfsoul avatar Dec 20 '23 12:12 sfsoul