鼠标悬停暂停倒计时,移开后从剩余时长继续的实现问题
实现鼠标移开后从暂停剩余时长继续的倒计时计时器
需求回顾
- 初始4秒倒计时,重置后回到4秒
- 鼠标悬停元素时计时器暂停
- 鼠标移开后,从暂停时的剩余时长继续倒计时(而非重置为4秒)
原代码问题分析
mouseEnterHandler中直接将remainingTimer设为autoplayInterval,会覆盖暂停时的真实剩余时间,导致无法恢复到正确位置mouseLeaveHandler中直接把timerStart设为当前时间,相当于重新从4秒开始计时,不符合需求
修改后的代码实现
const autoplayInterval = 4000; // ms const [remainingTimer, setRemainingTimer] = useState(autoplayInterval); const [timerStart, setTimerStart] = useState(Date.now()); const [mouseEntered, setMouseEntered] = useState(false); // 每16ms更新剩余时间(非暂停状态下) setTimeout(() => { if (mouseEntered) return; const currentTime = Date.now(); const diff = currentTime - timerStart; const newRemaining = Math.max(0, autoplayInterval - diff); setRemainingTimer(newRemaining); }, 16); const mouseEnterHandler = () => { // 暂停时仅标记状态,保留当前剩余时间 setMouseEntered(true); } const mouseLeaveHandler = () => { // 根据剩余时间计算新的起始点,确保从暂停位置继续 setTimerStart(Date.now() - (autoplayInterval - remainingTimer)); setMouseEntered(false); } return ( <div onMouseEnter={mouseEnterHandler} onMouseLeave={mouseLeaveHandler}> {/* 可在此处展示剩余时间,例如:{Math.round(remainingTimer / 1000)}秒 */} </div> )
关键修改点说明
- 初始化
remainingTimer为autoplayInterval,匹配初始4秒倒计时状态 - 鼠标进入时仅切换暂停标记,不修改剩余时间,保留暂停时的真实时长
- 鼠标离开时通过
Date.now() - (autoplayInterval - remainingTimer)计算新的timerStart:autoplayInterval - remainingTimer是已经流逝的时间- 当前时间减去已流逝时间,让计时器从对应进度点继续倒计时
- 更新剩余时间时加入
Math.max(0, ...),避免出现负数时间
内容的提问来源于stack exchange,提问作者Владислав Петров
相关产品推荐
相关产品推荐

