2023-10-10|閱讀時間 ‧ 約 4 分鐘

[ TS LeetCode 筆記 ] 2715. Timeout Cancellation.

題目:

Given a function fn, an array of arguments args, and a timeout t in milliseconds, return a cancel function cancelFn.

After a delay of tfn should be called with args passed as parameters unless cancelFn was invoked before the delay of t milliseconds elapses, specifically at cancelT ms. In that case, fn should never be called.


先備知識:

  • 包括對回調函數的了解、Rest參數的使用、clearTimeoutsetTimeout 方法的認識。

setTimeout 方法:

  • setTimeout 方法的工作原理: 接受一個回調函數和一個延遲時間(以毫秒為單位)。
  • 強調 setTimeout 引入了異步行為,使得JavaScript引擎可以在延遲計時器過程中繼續執行其他代碼。

clearTimeout 方法:

  • 解釋了為什麼需要使用 clearTimeout,它用於取消以前使用 setTimeout 設置的計時器。
  • 提到了 clearTimeout 通過傳遞計時器的唯一標識符(timeout ID)來取消回調函數的執行和計時器的停止。
  • 強調了 clearTimeout 允許控制計劃函數的執行,並提供了在計時器過程中暫停或取消計劃執行的能力。

應用場景:

  • clearTimeoutsetTimeout 的應用場景,包括動畫、事件處理、計劃和異步編程等。

結論:

  • 總結 clearTimeout 的重要性,它允許停止或取消計劃函數的執行,提高代碼的可控性和靈活性。
  • 強調 setTimeoutclearTimeout 為管理和調整代碼的定時提供強大的機制,有助於提高JavaScript程序的效率和響應性。

解題:

type JSONValue = null | boolean | number | string | JSONValue[] | { [key: string]: JSONValue };
type Fn = (...args: JSONValue[]) => void

/**
 * @param {Function} fn
 * @param {Array} args
 * @param {number} t
 * @return {Function}
 */
function cancellable(fn: Fn, args: JSONValue[], t: number): Function {
    const timer = setTimeout(()=> fn(...args), t);
    return () => clearTimeout(timer);
};


相關知識補給

如果不知道什麼是 Javascript Event Loop 可以參考這部影片,裡面介紹的非常詳細。


分享至
成為作者繼續創作的動力吧!
TypeScript LeetCode 以 TypeScript 為工具,深入解析 LeetCode 上的算法和資料結構問題,提供清晰解釋和程式碼示範,幫助您精進 TypeScript 技能,解決挑戰性問題,無論您的程式開發水平如何。讓我們一同鑽研、提升,迎接算法挑戰,成長技術專長!,快速提高您的技能水平
從 Google News 追蹤更多 vocus 的最新精選內容從 Google News 追蹤更多 vocus 的最新精選內容

發表回應

成為會員 後即可發表留言
© 2024 vocus All rights reserved.