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

Pomodoro Timer第二轮休息阶段出现负数向上计数问题求助

故障核心原因
  • 变量名拼写错误:你在全局声明的休息时长变量是breakSeconds,但在save()函数中你赋值的是拼写完全不同的breakMinutes,这属于JS新手非常常见的低级错误。JS遇到未声明的变量名会自动创建一个临时的全局变量,完全不会修改你原来的breakSeconds变量,第一轮休息倒计时结束后breakSeconds就变成了0,之后再也没有被重新赋值,第二轮休息阶段一开始就从0继续减,自然就出现负数递增的异常。
  • 小隐患:初始给workSeconds、breakSeconds赋值时用了带引号的字符串格式数字,虽然JS弱类型特性不会直接报错,但容易后续运算出现不可预期的问题,建议统一用数字类型赋值。
修复后的完整代码
// we need some variables to store the work and break minutes 
// 修复:初始值改为数字类型
var workSeconds = 120, breakSeconds = 60;
// and a referens to interval
var xInterval;

var audio = new Audio('Bell_finished.mp3');

// start function
function start() {          
    xInterval = setInterval(workCountDown, 1000);
}
// stop function
function stop() {
    clearInterval(xInterval);
}
// reset function; calls stop, save which re-stores the values of user inputs and then starts again.
function reset() {
    stop();
    save();
    start();
}
// save function that saves the values of user inputs
function save() {
    workSeconds = parseInt(document.getElementById("TaskTime").value)*60;
    // 修复:变量名和全局声明的breakSeconds保持一致
    breakSeconds = parseInt(document.getElementById("BreakTime").value)*60;           
}

// working count down function
function workCountDown() {
    // counting down work seconds
    workSeconds--;
    // showing work seconds in "0:0" format: 
    document.getElementById("timer").innerText = Math.floor((workSeconds / 60)).toString() + ":" + (workSeconds % 60).toString();
    
    // if workSeconds reaches to zero, stops the workInterval and starts the breakInterval:
    if (workSeconds == 0) {
        audio.play();
        console.log("relaxing...");
        clearInterval(xInterval);
        xInterval = setInterval(breakCountDown, 1000);
    }
}

// breaking count down function
function breakCountDown() {
    // counting down break seconds
    breakSeconds--;
    // showing break seconds in "0:0" format: 
    document.getElementById("timer").innerText = Math.floor((breakSeconds / 60)).toString() + ":" + (breakSeconds % 60).toString();
    
    // if breakSeconds reaches to zero, stops the breakInterval, resets the variables to initial values by calling save function and starts the workInterval again:
    if (breakSeconds == 0) {
        audio.play();
        console.log("ready to work...");
        reset();
    }
}
新手开发小提示

写代码时如果遇到变量值不符合预期的情况,可以在对应位置用console.log(变量名)打印变量值到浏览器控制台,能快速定位是变量名拼写错误还是赋值逻辑问题。

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.09.29 12:06:02