You need to enable JavaScript to run this app. JavaScript实现自动计数器时无法在指定数值停止,该如何解决?
优惠活动
大模型
产品
解决方案
定价
更多

JavaScript实现自动计数器时无法在指定数值停止,该如何解决?

问题原因

  • 没有存储setInterval返回的定时器ID,无法在达到目标数值时终止计数任务
  • 停止判断逻辑错误:将单个字符display_str[i]与完整的5位目标数值字符串做对比,永远无法触发停止逻辑,且原逻辑只是重置数字没有终止定时器
  • 目标数值判断位置错误,应该在每次数字更新完成后统一判断,不应该放在渲染单个字符的循环里

修正方案

你需要的效果是计数到00100时停止,修正后的完整代码如下:

<body onload="incrementCount()">
<div class="main_container" id="id_main_container">
  <div class="container_inner" id="display_div_id">
  </div>
</div>
</body>

<script>
var str_counter_0 = 0; // 个位
var str_counter_1 = 0; // 十位
var str_counter_2 = 0; // 百位
var str_counter_3 = 0; // 千位
var str_counter_4 = 0; // 万位
var display_div = document.getElementById("display_div_id");
// 存储定时器ID,用于后续停止
var timer = null;
// 定义目标数值:数组顺序对应万位、千位、百位、十位、个位
const TARGET = [0,0,1,0,0];

function incrementCount(){
  timer = setInterval(function(){
    // 清空原有渲染内容
    while (display_div.hasChildNodes()) {
        display_div.removeChild(display_div.lastChild);
    }
    // 数字自增进位逻辑
    str_counter_0++;
    if (str_counter_0 > 9) {
      str_counter_0 = 0;
      str_counter_1++;
    }
    if(str_counter_1>9){
      str_counter_1 = 0;
      str_counter_2++;
    }
    if(str_counter_2>9){
      str_counter_2 = 0;
      str_counter_3++;
    }
    if(str_counter_3>9){
      str_counter_3 = 0;
      str_counter_4++;
    }

    // 达到目标值时停止计数
    if(str_counter_4 === TARGET[0] 
      && str_counter_3 === TARGET[1]
      && str_counter_2 === TARGET[2]
      && str_counter_1 === TARGET[3]
      && str_counter_0 === TARGET[4]){
        clearInterval(timer);
    }

    // 渲染数字与间隔空格
    const numArr = [str_counter_4, str_counter_3, str_counter_2, str_counter_1, str_counter_0];
    numArr.forEach((num, index) => {
      const numSpan = document.createElement('span');
      numSpan.className = 'num_tiles';
      numSpan.innerText = num;
      display_div.appendChild(numSpan);
      // 最后一位数字后不需要加间隔空格
      if(index !== numArr.length -1){
        const spaceSpan = document.createElement('span');
        spaceSpan.innerText = '\xa0\xa0\xa0\xa0\xa0';
        display_div.appendChild(spaceSpan);
      }
    })
  },200);
} 
</script>

核心修改说明

  • 新增定时器变量存储setInterval返回值,达到目标值时调用clearInterval终止计数
  • 调整停止判断逻辑,数字更新完成后直接对比5位数值和目标值,逻辑清晰无匹配错误
  • 优化数字渲染逻辑,避免拼接字符串后拆分单个字符导致的逻辑混乱
  • 可通过修改TARGET数组自定义停止数值,数组第一位对应万位,最后一位对应个位

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.10.16 10:24:03