上次编辑到这里,代码来自缓存 点击恢复默认模板
/**
* @param {Function} fn
* @param {number} t
* @return {Function}
*/
var timeLimit = function(fn, t) {
return async function(...args) {
}
};
/**
* const limited = timeLimit((t) => new Promise(res => setTimeout(res, t)), 100);
* limited(150).catch(console.log) // "Time Limit Exceeded" at t=100ms
*/
typescript 解法, 执行用时: 72 ms, 内存消耗: 42.3 MB, 提交时间: 2023-09-12 10:04:23
type Fn = (...params: any[]) => Promise<any>;
function timeLimit(fn: Fn, t: number): Fn {
return async function(...args) {
let timer;
const timeoutPromise = new Promise((res,rej) => {
timer = setTimeout(() => rej('Time Limit Exceeded'), t)
});
return Promise.race([fn(...args),timeoutPromise]).then(res => {
clearTimeout(timer);
return res;
});
}
};
/**
* const limited = timeLimit((t) => new Promise(res => setTimeout(res, t)), 100);
* limited(150).catch(console.log) // "Time Limit Exceeded" at t=100ms
*/
javascript 解法, 执行用时: 52 ms, 内存消耗: 41 MB, 提交时间: 2023-04-17 15:27:57
/**
* @param {Function} fn
* @param {number} t
* @return {Function}
*/
var timeLimit = function(fn, t) {
return async function(...args) {
return Promise.race([
fn(...args),
new Promise((r,j) => setTimeout(() => j('Time Limit Exceeded'), t))
]);
}
};
/**
* const limited = timeLimit((t) => new Promise(res => setTimeout(res, t)), 100);
* limited(150).catch(console.log) // "Time Limit Exceeded" at t=100ms
*/