Topic Description

Given a function fn, an array of parameters args, and a timeout duration t in milliseconds, return a cancellation function cancelFn. cancelFn will be called after a delay of cancelTimeMs.

setTimeout(cancelFn,cancelTimeMs)

At the outset, the execution of the function fn should be delayed by t milliseconds. If the function cancelFn is called before the delay of t milliseconds, it should cancel the delayed execution of fn. If cancelFn is not called within the specified delay of t milliseconds, then fn should be executed with the provided args as parameters.

// example1
Input: fn = (x) => x * 5, args = [2], t = 20
Output: [{"time": 20, "returned": 10}]
Explain:
const cancelTimeMs = 50;
const cancelFn = cancelable((x) => x * 5, [2], 20);
setTimeout(cancelFn, cancelTimeMs);

fn(2) 在 20 毫秒時執行,而取消操作將這之後,延遲 cancelTimeMs(50毫秒)後被呼叫

// example2
Input: fn = (x) => x**2, args = [2], t = 100
Output: []
Explain:
const cancelTimeMs = 50;
const cancelFn = cancelable((x) => x**2, [2], 100);
setTimeout(cancelFn, cancelTimeMs);

因為取消函式 cancelTimeMs 在 50 毫秒時就被呼叫,所以在 100 毫秒時才會被執行的 fn(2) 不會被呼叫

Answer

function cancelable(fn, args, t){
	const timer = setTimeout(()=>{
		fn(...args)
	},t)
	return function cancelFn(){
		clearTimeout(timerId)
	}
}