Topic Description

Here's a handwritten repeat function that takes three parameters:

The repeat function will return an executable function that, when invoked, will repeat the func function times times, with an interval of wait milliseconds between each repetition.

function repeat (func, times, wait) {
  // ...your code
}

const repeatFunc = repeat(console.log, 3, 1000);
repeatFunc("Ya");    // 每 1 秒輸出一次 Ya,共輸出 3 次

Answer

function repeat(func, times, wait) {
  let count = 0;
  let timerId = null;

  function wrapper(...args) {
    if (count < times) {
      func(...args);
      count++;
      console.log('Here! count: ',count)
      timerId = setTimeout(wrapper, wait, ...args);
    } else {
      clearTimeout(timerId); // 清除最後一個計時器
    }
  }

  return wrapper;
}
function repeat(func, times, wait) {
  // repeat 會返回一個函式 
  return function wrapper(...args) {
    if (times > 0) {
      // 執行函函式
      func(...args);
      // 設定 times 毫秒後,再次呼叫 wrapper
      setTimeout(wrapper, wait, ...args);
      // 遞減 times 次數
      times--;
    }
  }
}
function repeat(func, times, wait) {
  let count = 0;

  return function wrapper(...args) {
    const intervalId = setInterval(() => {
      if (count < times) {
        func(...args);
        count++;
        console.log('Here! count: ',count)
      } else {
        clearInterval(intervalId);
      }
    }, wait);
  };
}