題目:
Given a function fn
, an array of arguments args
, and a timeout t
in milliseconds, return a cancel function cancelFn
.
After a delay of t
, fn
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參數的使用、
clearTimeout
和setTimeout
方法的認識。
setTimeout
方法:
setTimeout
方法的工作原理: 接受一個回調函數和一個延遲時間(以毫秒為單位)。- 強調
setTimeout
引入了異步行為,使得JavaScript引擎可以在延遲計時器過程中繼續執行其他代碼。
clearTimeout
方法:
- 解釋了為什麼需要使用
clearTimeout
,它用於取消以前使用setTimeout
設置的計時器。 - 提到了
clearTimeout
通過傳遞計時器的唯一標識符(timeout ID)來取消回調函數的執行和計時器的停止。 - 強調了
clearTimeout
允許控制計劃函數的執行,並提供了在計時器過程中暫停或取消計劃執行的能力。
應用場景:
clearTimeout
和setTimeout
的應用場景,包括動畫、事件處理、計劃和異步編程等。
結論:
- 總結
clearTimeout
的重要性,它允許停止或取消計劃函數的執行,提高代碼的可控性和靈活性。 - 強調
setTimeout
和clearTimeout
為管理和調整代碼的定時提供強大的機制,有助於提高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 可以參考這部影片,裡面介紹的非常詳細。