我正在编写简单的脚本,该脚本应该通过倒计时将给定值(例如 6345.23
)动画化为 0
,它也应该以 0 结束
如果指定的时间已经过去(例如2 秒
。
我从简单的逻辑开始:
- 给定配置:
初始值
、时间(秒)
、间隔
- 时间以秒为单位,因此请将其转换为毫秒
- 通过将时间(以毫秒为单位)除以间隔来计算刻度数
- 通过将初始值除以刻度数来计算每个刻度的减少值
一旦了解了上述内容,我们就可以简单地执行以下操作:(简单模型,而不是实际代码)
intId = setInterval(function() {
if(ticks_made === amount_of_ticks) {
clearInterval(intId);
} else {
value -= amount_per_tick;
// update view
}
}, interval);
实际代码:
var value = 212.45,
time = 2, // in seconds
interval = 20; // in milliseconds
var time_to_ms = time * 1000,
amount_of_ticks = time_to_ms / interval,
amount_per_tick = (value / amount_of_ticks).toFixed(5);
var start_time = new Date();
var ticks_made = 0;
var intId = setInterval(function() {
if(ticks_made === amount_of_ticks) {
console.log('start time', start_time);
console.log('end time', new Date());
console.log('total ticks: ', amount_of_ticks, 'decresed by tick: ', amount_per_tick);
clearInterval(intId);
} else {
value = (value - amount_per_tick).toFixed(5);
console.log('running', ticks_made, value);
}
ticks_made++;
}, interval);
链接fiddle (在控制台中您可以观察它是如何工作的)
如果您将时间设置为2(2秒)
,则可以,但如果您将时间设置为例如2.55(2.55秒)
,则它根本不会停止在0
,它会以负值的形式无限地流逝。
我如何修复它,以便无论在几秒钟内设置什么,它总是一一精确地进行,直到达到完美0
?
var value = 212.45,
time = 2, // in seconds
interval = 20; // in milliseconds
var time_to_ms = time * 1000,
amount_of_ticks = time_to_ms / interval,
amount_per_tick = (value / amount_of_ticks).toFixed(5);
var start_time = new Date();
var ticks_made = 0;
var intId = setInterval(function() {
if(ticks_made === amount_of_ticks) {
console.log('start time', start_time);
console.log('end time', new Date());
console.log('total ticks: ', amount_of_ticks, 'decresed by tick: ', amount_per_tick);
clearInterval(intId);
} else {
value = (value - amount_per_tick).toFixed(5);
console.log('running', ticks_made, value);
}
ticks_made++;
}, interval);
最佳答案
您依赖于 ticks_made === amount_of_ticks
完全匹配。由于四舍五入,您可能无法获得完全匹配的结果,因此您最好这样做:
if(ticks_made >= amount_of_ticks) {
关于javascript - 在给定时间内从 n 到 0 倒计时,负最终值,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/50247825/