[Medium] 手寫 Repeat

2024年3月7日

💎 加入 E+ 成長計畫 與超過 300+ 位軟體工程師一同在社群中成長,並且獲得更多的軟體工程學習資源

題目描述

手寫一個 repeat 函式,會接受三個參數,包含

  • func:要重複執行的函式
  • times:重複執行的次數
  • wait:每次重複之間的間隔時間

最後 repeat 會返回一個可執行函式,該函式執行時會重複執行  func  函式  times  次,每次間隔  wait  毫秒。

const repeatFunc = repeat(console.log, 3, 5000);
repeatFunc("ExplainThis"); // 每 5 秒輸出一次 ExplainThis,共輸出 3 次

本題解答

以下是本題的解答,詳細解題思路可以在 E+ 成長計畫看到

解法

function repeat(func, times, wait) {
  return wrapper function(...args) {
    if (times > 0) {
      func(...args);
      setTimeout(wrapper, wait, ...args);
      times--;
    }
  }
}
🧵 如果你想收到最即時的內容更新,可以在 FacebookInstagram 上追蹤我們