You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

启用timer()自动启动后,Stop与Reset按钮失效问题求助

Fix for Non-Functional Stop/Reset Buttons After Auto-Starting Timer

Hey there! I see the issue with your timer setup—let's break down why the Stop and Reset buttons aren't working once you auto-start the timer, and fix it up.

The Root Cause

Your current timer uses a recursive chain of setTimeout calls: the timer() function triggers add(), and add() calls timer() again at the end. When you click Stop to run clearTimeout(t), you only clear the current pending timeout—but by that point, add() has already fired another timer() and created a new timeout. This means the timer keeps ticking, making it seem like the Stop button does nothing.

On top of that, the Reset button only resets the display and time variables without stopping the ongoing timer, so it just starts counting from 0 right away instead of staying stopped.


Fixed Full Code

I've rewritten the timer logic to use setInterval (which is easier to control for recurring tasks) and fixed the button functionality. Here's the complete working code:

const startstop = () => {};
var clicks = 0;
function onClick() {
 clicks += 1;
 document.getElementById("clicks").innerHTML = clicks;
};
const input = parseInt(prompt("Enter a SAMS number: "));
var SAMSINPUT = input;
document.getElementById('output').innerHTML = SAMSINPUT;
var goal = 0;
var output2 = document.getElementById('output2');
setInterval(function doIncrement() {
 goal += 1;
 output2.innerHTML = goal.toString();
}, SAMSINPUT * 1000)

var timerDiv = document.getElementById('timerValue'),
 start = document.getElementById('start'),
 stop = document.getElementById('stop'),
 reset = document.getElementById('reset'),
 timerInterval = null; // 存储定时器实例,用于启停控制

// Get time from cookie
var cookieTime = null;
//getCookie('time'); // 取消注释可测试cookie功能

// 初始化计时器状态
if (cookieTime != null && cookieTime != '00:00:00') {
 var savedCookie = cookieTime;
 var initialSegments = savedCookie.split('|');
 var savedTimer = initialSegments[0];
 var timerSegments = savedTimer.split(':');
 var seconds = parseInt(timerSegments[2]),
 minutes = parseInt(timerSegments[1]),
 hours = parseInt(timerSegments[0]);
 updateTimerDisplay();
 startTimer(); // 启动计时器
 $('#stop').removeAttr('disabled');
 $('#reset').removeAttr('disabled');
} else {
 var seconds = 0, minutes = 0, hours = 0;
 timerDiv.textContent = "00:00:00";
}

// 设置cookie过期时间
var curdate = new Date();
var exp = new Date();
exp.setTime(exp + 2592000000); // 30天过期

// 更新计时器显示内容
function updateTimerDisplay() {
 timerDiv.textContent = 
   (hours ? (hours > 9 ? hours : "0" + hours) : "00") + ":" +
   (minutes ? (minutes > 9 ? minutes : "0" + minutes) : "00") + ":" +
   (seconds > 9 ? seconds : "0" + seconds);
 // 取消注释可启用cookie存储
 // var timerTime = timerDiv.textContent.replace("%3A", ":");
 // setCookie('time', timerTime + '|' + curdate, exp);
}

// 时间递增逻辑
function addTime() {
 seconds++;
 if (seconds >= 60) {
 seconds = 0;
 minutes++;
 if (minutes >= 60) {
 minutes = 0;
 hours++;
 }
 }
 updateTimerDisplay();
}

// 启动计时器
function startTimer() {
 if (!timerInterval) { // 避免重复启动多个定时器
   timerInterval = setInterval(addTime, 1000);
 }
}

// 停止计时器
function stopTimer() {
 clearInterval(timerInterval);
 timerInterval = null; // 重置定时器实例
}

// 重置计时器
function resetTimer() {
 stopTimer();
 seconds = 0;
 minutes = 0;
 hours = 0;
 updateTimerDisplay();
 // setCookie('time', "00:00:00", exp); // 取消注释可重置cookie
}

// 自动启动计时器
startTimer();

/* 按钮事件绑定 */
start.onclick = function() {
 startTimer();
 $('#stop').removeAttr('disabled');
 $('#reset').removeAttr('disabled');
};

stop.onclick = function() {
 stopTimer();
 $(this).prop('disabled', 'disabled');
};

reset.onclick = function() {
 resetTimer();
 $(this).prop('disabled', 'disabled');
 $('#stop').prop('disabled', 'disabled');
};

/**
 * Cookie操作函数
 * */
function setCookie(name, value, expires) {
 document.cookie = name + "=" + value + "; path=/" + ((expires == null) ? "" : "; expires=" + expires.toGMTString());
}
function getCookie(name) {
 var cname = name + "=";
 var dc = document.cookie;
 if (dc.length > 0) {
 begin = dc.indexOf(cname);
 if (begin != -1) {
 begin += cname.length;
 end = dc.indexOf(";", begin);
 if (end == -1) end = dc.length;
 return unescape(dc.substring(begin, end));
 }
 }
 return null;
}
body {
 background-color: powderblue;
}
p {
 color: red;
}
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<body>
 <p>
 SAMS VALUE: <span id="output"></span>
 </p>
 <p>
 GOAL: <span id="output2"></span>
 </p>
 <button style="background-color:green" type="button" onClick="onClick()">ACTUAL</button>
 <p>Actual Count: <span id="clicks">0</span></p>
 <div class="container">
 <div class="row">
 <div class="col-sm-4"></div>
 <div class="col-sm-4">
 <div id="timeContainer" class="well well-sm">
 <time id="timerValue"></time>
 </div>
 <div id="timerButtons">
 <button id="start" class="btn btn-success">START</button>
 <button id="stop" class="btn btn-danger" disabled="disabled">STOP</button>
 <button id="reset" class="btn btn-default" disabled="disabled">RESET</button>
 </div>
 </div>
 <div class="col-sm-4"></div>
 </div>
 </div>
</body>

Key Fixes Explained

  • Switched to setInterval: Unlike recursive setTimeout, setInterval creates a single repeating timer instance that can be fully stopped with clearInterval, eliminating the endless chain of pending timeouts.
  • Added timerInterval variable: Stores the unique ID of the active timer, ensuring we always target the correct instance when stopping or starting.
  • Split logic into dedicated functions: Separated timer display updates, time incrementing, and control logic into individual functions for better readability and maintainability.
  • Fixed Reset functionality: Now stops the timer first before resetting values, so the timer stays at 0 until manually restarted.
  • Improved button state management: Auto-start correctly enables Stop/Reset buttons, and Reset disables both buttons to match the stopped state.

内容的提问来源于stack exchange,提问作者J S

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.05.09 06:27:39