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

点击按钮后展示用户输入值对应动态乘法表的功能如何实现?

现有代码问题
  • 核心逻辑错误:updateAnimation 内写了两层for循环,单次调用就会快速遍历完1-9的所有乘法结果,页面只会显示最终的9乘输入值的结果,完全无法实现每秒切换的动画效果
  • 定时器清除错误:stopAnimation 中 clearTimeout 传入的参数是函数名updateAnimation,正确参数应该是定时器IDcounterAnimation,导致停止功能完全失效
  • 全局计数器未使用:初始化的counter变量没有被用到,没有实现乘数1-9循环递增、重置的逻辑
  • 展示格式不符合需求:页面只显示乘积结果,没有按照要求输出「乘数 × 输入值 = 乘积」的完整文本
修正后代码

JS部分

var counter;
var animationOn = false;
var counterAnimation;

function updateAnimation() {
  // 动画未开启直接返回
  if (!animationOn) return;
  // 获取输入值转数字格式
  const value = Number(document.getElementById('value1').value);
  // 计算当前乘法结果并更新展示内容
  const product = counter * value;
  const counterSpan = document.getElementById("counterHolder");
  counterSpan.innerHTML = `${counter} × ${value} = ${product}`;
  // 计数器自增,超过9就重置为1实现循环
  counter++;
  if (counter > 9) {
    counter = 1;
  }
  // 注册下一秒的更新任务
  counterAnimation = setTimeout(updateAnimation, 1000);
}

function startAnimation() {
  if (animationOn == false) {
    animationOn = true;
    counter = 1;
    // 立刻执行第一次更新,无需等待1秒延迟
    updateAnimation();
  }
}

function stopAnimation() {
  if (animationOn == true) {
    animationOn = false;
    // 传入正确的定时器ID清除定时任务
    clearTimeout(counterAnimation);
  }
}

HTML部分(仅做语法规范优化,核心结构不变)

<body>
  <button onclick="startAnimation();">
    Start animation 
  </button>
  <button onclick="stopAnimation();">
    Stop animation
  </button><br><br>
  <label>Enter an integer: </label>
  <input type="number" size="20" id="value1" name="value">
  <span id="counterHolder">0</span>
</body>

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.10.03 03:18:02