动手实现一个 repeat 方法

文章介绍了两种在JavaScript中实现repeat方法的方式,一种是使用async/await和sleep函数,另一种是递归调用并利用setTimeout。这两种方法分别演示了如何让一个函数按指定次数和间隔重复执行。

动手实现一个 repeat 方法

function repeat(func, times, wait) {
  // TODO
}
const repeatFunc = repeat(alert, 4, 3000);
// 调用这个 repeatFunc ("hellworld"),会alert4次 helloworld, 每次间隔3秒

 方法一:

async function sleep(fn, wait, args) {
  return new Promise((resolve) => {
    setTimeout(() => {
      fn.apply(this, args)
      resolve()
    }, wait)
  })
}
function repeat(func, times, wait) {
  return async function() {
    for (let i = 0; i < times; i++) {
      await sleep(func, wait, arguments)
    }
  }
}
var repeatFunc = repeat(alert, 4, 3000);
repeatFunc('helloworld')

方法二:

function repeat(func, times, wait) {
  return function(...args) {
    const _this = this;
    function recursiveCall(count) {
      if (count > 0) {
        setTimeout(() => {
          func.apply(_this, args);
          recursiveCall(count - 1);
        }, wait);
      }
    }
    recursiveCall(times);
  };
}
var repeatFunc = repeat(alert, 4, 3000);
repeatFunc('helloworld');

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值