Skip to content

Latest commit

 

History

History
55 lines (50 loc) · 1.39 KB

Question_2725.md

File metadata and controls

55 lines (50 loc) · 1.39 KB

LeetCode Records - Question 2725 Interval Cancellation

Attempt 1: Use setInterval() and clearInterval()

/**
 * @param {Function} fn
 * @param {Array} args
 * @param {number} t
 * @return {Function}
 */
var cancellable = function(fn, args, t) {
    fn(...args);
    
    const timer = setInterval(() => {
        fn(...args);
    }, t);

    return () => {
        clearInterval(timer);
    }
};

/**
 *  const result = [];
 *
 *  const fn = (x) => x * 2;
 *  const args = [4], t = 35, cancelTimeMs = 190;
 *
 *  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);
 *
 *  setTimeout(cancel, cancelTimeMs);
 *   
 *  setTimeout(() => {
 *      console.log(result); // [
 *                           //     {"time":0,"returned":8},
 *                           //     {"time":35,"returned":8},
 *                           //     {"time":70,"returned":8},
 *                           //     {"time":105,"returned":8},
 *                           //     {"time":140,"returned":8},
 *                           //     {"time":175,"returned":8}
 *                           // ]
 *  }, cancelTimeMs + t + 15)    
 */
  • Runtime: 61 ms (Beats: 82.47%)
  • Memory: 49.65 MB (Beats: 32.55%)