上次编辑到这里,代码来自缓存 点击恢复默认模板
/**
* @param {Function} fn
* @param {Array} args
* @param {number} t
* @return {Function}
*/
var cancellable = function(fn, args, t) {
};
/**
* const result = []
*
* const fn = (x) => x * 5
* const args = [2], t = 20, cancelT = 50
*
* const log = (...argsArr) => {
* result.push(fn(...argsArr))
* }
*
* const cancel = cancellable(fn, args, t);
*
* setTimeout(() => {
* cancel()
* console.log(result) // [{"time":20,"returned":10}]
* }, cancelT)
*/
javascript 解法, 执行用时: 76 ms, 内存消耗: 41.3 MB, 提交时间: 2023-06-04 09:24:23
/**
* @param {Function} fn
* @param {Array} args
* @param {number} t
* @return {Function}
*/
var cancellable = function(fn, args, t) {
const id = setTimeout(() => {
fn(...args);
}, t);
return () => clearTimeout(id);
};
/**
* const result = []
*
* const fn = (x) => x * 5
* const args = [2], t = 20, cancelT = 50
*
* const log = (...argsArr) => {
* result.push(fn(...argsArr))
* }
*
* const cancel = cancellable(fn, args, t);
*
* setTimeout(() => {
* cancel()
* console.log(result) // [{"time":20,"returned":10}]
* }, cancelT)
*/
typescript 解法, 执行用时: 68 ms, 内存消耗: 42.4 MB, 提交时间: 2023-06-04 09:23:45
const cancellable = (fn: Function, args: any[], t: number): Function => {
const id = setTimeout(() => {
fn(...args);
}, t);
return () => clearTimeout(id);
};
/**
* const result = []
*
* const fn = (x) => x * 5
* const args = [2], t = 20, cancelT = 50
*
* const log = (...argsArr) => {
* result.push(fn(...argsArr))
* }
*
* const cancel = cancellable(fn, args, t);
*
* setTimeout(() => {
* cancel()
* console.log(result) // [{"time":20,"returned":10}]
* }, cancelT)
*/