Topic Description

Given a function fn, an array of parameters args, and a time interval t, return a cancellation function cancelFn. The cancellation function cancelFn will be called after a delay of cancelTimeMs milliseconds.

setTimeout(cancelFn, cancelTimeMs)

The function fn should be invoked immediately with the parameters args, and then called every t milliseconds until cancelTimeMs milliseconds, at which point cancelFn will be invoked.

// example
Input: fn = (x) => x * 2, args = [4], t = 35, cancelT = 190

Output:
[
   {"時間": 0, "返回": 8},
   {"時間": 35, "返回": 8},
   {"時間": 70, "返回": 8},
   {"時間": 105, "返回": 8},
   {"時間": 140, "返回": 8},
   {"時間": 175, "返回": 8},
]

解釋: 
const cancelTimeMs = 190;
const cancelFn = cancellable((x) => x * 2, [4], 35);
setTimeout(cancelFn, cancelTimeMs);

每隔35ms,呼叫fn(4)。直到 t = 190 ms,然後取消。
第一次呼叫 fn 是在 0ms,fn(4) 返回8。
第二次呼叫 fn 是在 35ms,fn(4) 返回8。
第三次呼叫 fn 是在 70ms,fn(4) 返回8。
第四次呼叫 fn 是在 105ms,fn(4) 返回8。
第五次呼叫 fn 是在 140ms,fn(4) 返回8。
第六次呼叫 fn 是在 175ms,fn(4) 返回8。
在 t = 190 ms 時取消

Answer

function cancelable(fn, args, t){
	fn(...args)
	
	const intervalId = setInterval(()=>{
		fn(...args)
	}, t)
	
	return function cancelFn(){
		clearInterval(intervalId)
	}
}