如何实现数值递增时逐阶显示而非直接跳数?
解决方案
核心思路是把一次性的总增量拆分为逐次+1的小步,在1秒周期内完成所有增量,同时保留原有的1秒定时器逻辑,避免维护复杂的时间间隔。
修改后的代码
numbersGoingUp() { const atoms = this.user.resources[0]; const molecules = this.user.resources[1]; const atom_gens = this.user.generators[0]; const molecule_gens = this.user.generators[1]; if (!this.interval) { this.interval = setInterval(() => { if (atom_gens.active) { // 计算原子每秒总增量 const atomTotal = atom_gens.amount; this.stepIncrement(atoms, atomTotal); if (molecule_gens.active) { const moleculeTotal = molecule_gens.amount; this.stepIncrement(molecules, moleculeTotal); } } }, 1000); } }, // 逐次递增工具函数 stepIncrement(resource, total) { let remaining = total; // 计算每步间隔,确保1秒内完成所有增量 const stepGap = 1000 / total; const addOne = () => { if (remaining <= 0 || resource.amount >= resource.max) return; resource.amount += 1; remaining -= 1; setTimeout(addOne, stepGap); }; addOne(); }
方案说明
- 保留原有的1秒定时器作为周期触发源,不用调整核心时间逻辑,降低维护成本。
- 新增
stepIncrement函数处理逐次递增:自动计算每步的时间间隔,确保在1秒内完成设定的总增量,同时实现1→2→3...的平滑显示。 - 兼容原有逻辑:当资源达到最大值时自动停止递增,原子和分子的增量逻辑复用同一个工具函数,代码更简洁。
内容的提问来源于stack exchange,提问作者Tristan Lovasz
相关产品推荐
相关产品推荐

