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

jQuery计数器无法从0递增到目标值,求代码修正

问题分析

你当前的代码使用同步for循环更新数值,JS同步执行过程中会阻塞浏览器UI渲染,循环会在极短时间内执行完成,无法看到逐步递增的动画效果,只会直接显示最终数值,不符合需求。

修正后使用setInterval实现的代码
$(document).ready(function() {
    $('.tts-counter .tts-counter-item .tts-number').each(function() {
        // 提前存储当前元素的jQuery引用,避免定时器内this指向错误
        const $this = $(this);
        const targetValue = parseInt($this.data('counter'));
        let currentValue = 0;
        // 定时器间隔单位为毫秒,数值越小增速越快,可自行调整
        const speed = 30;

        const timer = setInterval(function() {
            currentValue++;
            $this.text(currentValue);
            // 达到目标值后清除定时器,避免内存泄漏
            if (currentValue >= targetValue) {
                clearInterval(timer);
            }
        }, speed);
    });
});
可调整参数说明
  • 调整speed变量的数值可以改变计数速度,数值越小动画越快
  • 如果目标数值很大,不想等待太久,可以修改currentValue++为更大的步长,比如currentValue += 5,同时可以对应调大speed数值让动画更流畅

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.10.21 23:45:04