iT邦幫忙

2023 iThome 鐵人賽

DAY 14
0
Software Development

LeetCode-30 Days of JavaScript系列 第 14

LeetCode JS30-Day14 | 2715. Timeout Cancellation 執行可取消的延遲函數

  • 分享至 

  • xImage
  •  

Day14 - 2715.Timeout Cancellation 執行可取消的延遲函數 EASY

Description❓

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 處)

Points

Solution✍️

[ ▶️挑戰這一題 ][ 本日代碼 ]

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;
};

Testcase

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}

上一篇
LeetCode JS30-Day13 |2621. Sleep 睡眠函式
下一篇
LeetCode JS30-Day15 | 2725. Interval Cancellation 間隔取消
系列文
LeetCode-30 Days of JavaScript30
圖片
  直播研討會
圖片
{{ item.channelVendor }} {{ item.webinarstarted }} |
{{ formatDate(item.duration) }}
直播中

尚未有邦友留言

立即登入留言