2676. 节流
2024年4月13日大约 1 分钟
2676. 节流
type F = (...args: number[]) => void
function throttle(fn: F, t: number): F {
let lastArgs: number[] = []
let nextRunTime = 0
let timer
return function (...args) {
const now = new Date().getTime()
if (now >= nextRunTime) {
nextRunTime = now + t
fn(...args)
} else {
clearTimeout(timer)
lastArgs = [...args]
timer = setTimeout(() => {
nextRunTime = Date.now() + t
fn(...lastArgs!)
lastArgs = []
timer = null
}, nextRunTime - now)
}
}
}
/**
* const throttled = throttle(console.log, 100);
* throttled("log"); // logged immediately.
* throttled("log"); // logged at t=100ms.
*/题目要点
「2676. 节流」关注的是异步调度语义:并发上限、任务顺序、失败传播以及资源释放时机。
思路拆解
- 先明确时序模型:谁创建任务、谁消费任务、完成后如何回收。
- 把控制逻辑拆成“调度器 + 执行器”,降低状态耦合。
- 明确成功/失败分支的行为是否对齐题目预期(中断、继续或聚合返回)。
复杂度分析
- 时间复杂度:由任务总数与单任务耗时共同决定,调度本身通常是线性的。
- 空间复杂度:关注并发窗口内的任务状态、结果缓存与错误对象。
边界与测试
- 空任务列表、并发数为 1、并发数大于任务数。
- 同时成功与失败的混合输入。
- 长任务与短任务混跑下的顺序与吞吐表现。
工程实践
显式维护任务状态(pending/running/settled),并把异常路径纳入同一返回协议,避免“静默失败”。
总结
异步题的核心不是 API 记忆,而是时序建模能力。只要调度模型清晰,代码可读性和稳定性都会提升。
