秒表计时器(Timeout 实现 Interval)

时间:2025-03-30 09:25:37
const timerIdList = {}; mySetInterval(fn: (time: number) => void, delay: number) { const key = Symbol(); const interval = () => { const start = Date.now(); this.timerIdList[key] = setTimeout(() => { const end = Date.now(); const excuTime = end - start; try { fn(excuTime); } catch (e) { throw e.toString(); } interval(); }, 1000, false); }; setTimeout(interval, delay); return key; } myClearInterval(key: symbol) { if (key in this.timerIdList) { clearTimeout(this.timerIdList[key]); delete this.timerIdList[key]; } }