题目:2725.间隔取消

​​题目来源:

        leetcode题目,网址:2725. 间隔取消 - 力扣(LeetCode)

解题思路:

        利用 setInterval()每隔一段时间执行,利用闭包获取停止时间。 

解题代码:

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

/**
 *  const result = []
 *
 *  const fn = (x) => x * 2
 *  const args = [4], t = 35, cancelT = 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()
 *  }, cancelT)
 *   
 *  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}
 *                         //  ]
 *  }, cancelT + t + 15)    
 */
 
  

总结:

        抄的。        

        setTimeOut();  //在指定的毫秒数后调用函数或计算表达式

        setInterval();        //每隔一定时间调用函数、方法或对象


你可能感兴趣的:(#,JavaScript,leetcode,JavaScript)