gpt4 book ai didi

javascript - 带毫秒的 JQuery 倒数计时器

转载 作者:数据小太阳 更新时间:2023-10-29 04:07:08 24 4
gpt4 key购买 nike

我有一个非常基本的轻量级功能,从 30 秒开始倒计时。我一直在尝试为其添加毫秒数,但似乎无法使其正常工作。

var count = 30;
var counter = setInterval(timer, 1000); //1000 will run it every 1 second

function timer() {
if (count <= 0) {
clearInterval(counter);
return;
}
count = count - 1;
document.getElementById("timer").innerHTML = count + " secs"; // watch for spelling
}

最佳答案

试一试 this way .无论如何,秒表只计算百分之一秒。

var count = 3000;

var counter = setInterval(timer, 10); //10 will run it every 100th of a second

function timer()
{
if (count <= 0)
{
clearInterval(counter);
return;
}
count--;
document.getElementById("timer").innerHTML=count /100+ " secs";
}

Just for better formatting and testing :

HTML

<span id="timer"></span>

<button id="start">start</button>
<button id="stop">stop</button>
<button id="reset">reset</button>

Javascript

var initial = 30000;
var count = initial;
var counter; //10 will run it every 100th of a second

function timer() {
if (count <= 0) {
clearInterval(counter);
return;
}
count--;
displayCount(count);
}

function displayCount(count) {
var res = count / 100;
document.getElementById("timer").innerHTML = res.toPrecision(count.toString().length) + " secs";
}

$('#start').on('click', function () {
clearInterval(counter);
counter = setInterval(timer, 10);
});

$('#stop').on('click', function () {
clearInterval(counter);
});

$('#reset').on('click', function () {
clearInterval(counter);
count = initial;
displayCount(count);
});

displayCount(initial);

编辑:

最初的问题是想弄清楚如何像秒表一样显示,我知道很少有人真正计算毫秒。也就是说,here是一个可能的解决方案。它依赖于尽可能快地更新,并获取上次更新与当前更新之间的差异以保持准确。

var initial = 300000;
var count = initial;
var counter; //10 will run it every 100th of a second
var initialMillis;

function timer() {
if (count <= 0) {
clearInterval(counter);
return;
}
var current = Date.now();

count = count - (current - initialMillis);
initialMillis = current;
displayCount(count);
}

function displayCount(count) {
var res = count / 1000;
document.getElementById("timer").innerHTML = res.toPrecision(count.toString().length) + " secs";
}

$('#start').on('click', function () {
clearInterval(counter);
initialMillis = Date.now();
counter = setInterval(timer, 1);
});

$('#stop').on('click', function () {
clearInterval(counter);
});

$('#reset').on('click', function () {
clearInterval(counter);
count = initial;
displayCount(count);
});

displayCount(initial);

关于javascript - 带毫秒的 JQuery 倒数计时器,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/22385368/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com