使用jQuery实现点击开始按钮重置并启动倒计时(解决多次点击加速问题)
Hey there! The problem you’re facing happens because every time you click the Start button, you spin up a new setInterval timer without stopping the old one. Multiple timers running side-by-side make the countdown speed up like crazy. Let’s fix this by merging the reset functionality into the Start button and ensuring only one timer runs at a time.
Step 1: Update the JavaScript Logic
We’ll tweak the code to:
- Clear any existing timer before starting a new one
- Reset the
minutesandsecondsvalues every time Start is clicked - Keep the core countdown logic intact but make it safe to re-run
var interval; // Store default timer values so we can reset to them easily var defaultMinutes = 5; var defaultSeconds = 10; var minutes = defaultMinutes; var seconds = defaultSeconds; function countdown(element) { // Stop any existing timer first to prevent acceleration clearInterval(interval); // Reset the timer to its initial values minutes = defaultMinutes; seconds = defaultSeconds; interval = setInterval(function() { var el = document.getElementById(element); if (seconds === 0) { if (minutes === 0) { el.innerHTML = "countdown's over!"; alert("countdown's over!"); clearInterval(interval); return; } else { minutes--; seconds = 60; } } // Build the display text cleanly var minuteText = minutes > 0 ? `${minutes} ${minutes > 1 ? 'minutes' : 'minute'}` : ''; var secondText = `${seconds} ${seconds > 1 ? 'seconds' : 'second'}`; var displayText = `${minuteText} ${secondText} remaining`.trim(); el.innerHTML = displayText; seconds--; }, 1000); } // Optional: Keep the dedicated reset button if you still want it function resetTimer() { clearInterval(interval); minutes = defaultMinutes; seconds = defaultSeconds; document.getElementById('countdown').innerHTML = `${defaultMinutes} minutes ${defaultSeconds} seconds remaining`; }
Step 2: Update the HTML
Adjust the Start button to call our improved countdown function, and keep the Reset button (optional, since Start now handles resetting):
<div id='countdown'>5 minutes 10 seconds remaining</div> <input type="button" onclick="countdown('countdown');" value="Start" /> <input type="button" onclick="resetTimer();" value="Reset" />
Key Changes Breakdown
clearInterval(interval)at the start: This stops any running timer before starting a new one, eliminating the "speeding up" problem entirely.- Resetting to default values: Ensures every Start click begins fresh from 5 minutes 10 seconds, not where the last timer left off.
- Cleaner display text: Used template literals for readability, and
.trim()to avoid extra spaces when minutes hit 0. - Optional reset function: If you still want a dedicated Reset button, it will stop the timer and reset the display to the initial state.
Now, clicking Start multiple times will always reset the timer and start fresh without any weird acceleration!
内容的提问来源于stack exchange,提问作者umar bhatti
相关产品推荐
相关产品推荐

