문제

Given a function fn, an array of arguments args, and a timeout t in milliseconds, return a cancel function cancelFn.

After a delay of cancelTimeMs, the returned cancel function cancelFn will be invoked.

setTimeout(cancelFn, cancelTimeMs)
Initially, the execution of the function fn should be delayed by t milliseconds.

If, before the delay of t milliseconds, the function cancelFn is invoked, it should cancel the delayed execution of fn. Otherwise, if cancelFn is not invoked within the specified delay t, fn should be executed with the provided args as arguments.

 

예제

 

풀이

/**
 * @param {Function} fn
 * @param {Array} args
 * @param {number} t
 * @return {Function}
 */
var cancellable = function(fn, args, t) {
    const timeout = setTimeout(function () {
        fn(...args);
    }, t)
    
    return function() {
        clearTimeout(timeout);
    }
};

/**
 *  const result = [];
 *
 *  const fn = (x) => x * 5;
 *  const args = [2], t = 20, cancelTimeMs = 50;
 *
 *  const start = performance.now();
 *
 *  const log = (...argsArr) => {
 *      const diff = Math.floor(performance.now() - start);
 *      result.push({"time": diff, "returned": fn(...argsArr)});
 *  }
 *       
 *  const cancel = cancellable(log, args, t);
 *
 *  const maxT = Math.max(t, cancelTimeMs);
 *           
 *  setTimeout(cancel, cancelTimeMs);
 *
 *  setTimeout(() => {
 *      console.log(result); // [{"time":20,"returned":10}]
 *  }, maxT + 15)
 */

먼저, setTimeout 함수를 이용하여 t 밀리초 후에 fn 함수가 실행되게끔 만든다. 하지만 주석 코드에서 cancelTimeMs 밀리초가 지나면 `setTimeout(cancel, cancelTimeMs);` 코드에 의해 cancel 함수가 실행되는데, 이 때 cancellable 함수의 return 문에 의해 기존에 진행시켰던 setTimeout 함수를 clear시킨다.

따라서 t 밀리초보다 cancelTimeMs 밀리초가 더 짧을 경우 정상적으로 setTimeout 함수가 t 밀리초 후 fn 함수를 호출하게 되지만 그렇지 않을 경우에는 clearTimeout이 먼저 실행되어 fn 함수를 호출하지 않게 된다.

'Algorithm' 카테고리의 다른 글

[LeetCode] 2704. To Be Or Not To Be  (0) 2024.02.05
[LeetCode] 2695. Array Wrapper  (0) 2024.01.31
[LeetCode] 2677. Chunk Array  (0) 2024.01.31
[BOJ] 4779. 칸토어 집합  (1) 2024.01.30
[SWEA] 1230. 암호문3  (1) 2024.01.29

+ Recent posts