EASY
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.
給定一個函數 fn、一個參數陣列 args 和一個以毫秒為單位的超時 t,傳回一個取消函數 cancelFn。
延遲 t 後,應使用作為參數傳遞的 args 來調用 fn,除非延遲 t 秒的過程中呼叫cancelFn,則fn將不被調用。
(特別是在 cancelT ms 處)
let result=[];
const cancellable = function(fn,args,t){
const startTime = Date.now();
let fnCalled = false;
let timeoutId = setTimeout(() => {
if (!fnCalled) {
fnCalled = true;
returnedVal=fn(...args);
const endTime = Date.now();
const elapsedTime = endTime - startTime;
result.push( {
'time':elapsedTime,
'returned':returnedVal,
});
console.log(result);
}
}, t);
const cancelFn = ()=>{
if (!fnCalled) {
clearTimeout(timeoutId);
const endTime = Date.now();
const elapsedTime = endTime - startTime;
console.log(`The cancellation was scheduled to occur after a delay of cancelT (${elapsedTime}ms).`);
}
};
return cancelFn;
};
const fn = (x) => x * 5;
const args = [2];
const t = 20;
const cancelT = 50;
const cancel = cancellable(fn, args, t);
setTimeout(cancel, cancelT); //cancelT毫秒後取消定時器
// output:
// [{…}]
// 0: {time: 21, returned: 10}
const fn2 = (x) => x**2
const args2 = [2];
const t2 = 100;
const cancelT2 = 50; //當 cancelT< t 時,fn 不應該被調用
const cancel2 = cancellable(fn2, args2, t2);
setTimeout(cancel2,cancelT2);
//output:
//The cancellation was scheduled to occur after a delay of cancelT (53ms).
const fn3 = (x1, x2) => x1 * x2
const args3 = [2,4];
const t3 = 30;
const cancelT3 = 100;
const cancel3 = cancellable(fn3, args3, t3);
setTimeout(cancel3,cancelT3);
//output:
//[{…}]
//0: {time: 31, returned: 8}