[ TS LeetCode 筆記 ] 2715. Timeout Cancellation.

閱讀時間約 3 分鐘

題目:

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 可以參考這部影片,裡面介紹的非常詳細。


毛怪
毛怪
不務正業的軟體工程師|今年29|仍然在探索自己想要的生活|心中的困惑太多,就把這些都記錄在這裡跟大家分享吧
留言0
查看全部
發表第一個留言支持創作者!