我有一个非常基本的轻量级功能,从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
}
答案 0 :(得分:9)
试一试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);
答案 1 :(得分:3)
问题是浏览器不可能每毫秒处理操作DOM 。出于这个原因,许多浏览器实际上为间隔设置了最小值 - 而W3C建议至少4ms (source)。我们可以使用此信息创建尽快运行的throttled approach。
// We actually only run our method every x millisecs, due to browser constraints
var THROTTLE_AMOUNT = 4;
countdown(30);
function countdown(secs) {
var milli = secs * (1000);
var counter = setInterval(function() {
if(milli <= 0) {
clearInterval(counter);
return
}
milli -= THROTTLE_AMOUNT;
document.getElementById("timer").innerHTML = milli + " millisecs"; // watch for spelling
}, THROTTLE_AMOUNT);
}
答案 2 :(得分:0)
你可以试试这个。如果您的目标是现代浏览器,则可以访问Performance
API,它会提供高分辨率的时间戳而不是正常的时间戳。
改进的解决方案将使用requestAnimationFrame()
。即使可能使用setTimeout(),每毫秒更新DOM也是浪费资源,因为浏览器通常只刷新屏幕60秒(每16.6毫秒)。在该间隔内更新时钟两次或更多时间将是无用的,并且用户将只看到最后一个值。
function now() {
return window.performance ? window.performance.now() : Date.now();
}
var count = 30000;
var delay = 20; //20 ms. This will be only indicative. There's no guarantee the browswer will call the function after exactly this time
var initTick = 0;
var timerElement = document.getElementById("timer");
function tick() {
var remaining = (count - (now() - initTick)) / 1000;
console.log(remaining);
remaining = remaining >= 0 ? remaining : 0;
var secs = remaining.toFixed(2);
timerElement.innerHTML = secs + " secs";
if (remaining) setTimeout(tick, delay);
}
initTick = now();
console.log(now());
setTimeout(tick, delay);
答案 3 :(得分:0)
This may help you:
var count = 30;
var count1 = 60;
//1000 will run it every 1 second
var counter1;
var counter = setInterval(timer, 1000);
function timer1() {
if (count1 <= 0 && count < 1) {
clearInterval(counter1);
return;
} else {
if (count1 <= 0 && count > 0)
count1 = 60;
else
count1 = count1 - 1;
//var counter=setInterval(timer, 1000);
}
document.getElementById("timer").innerHTML = count + "." + count1 + " secs"; // watch for spelling
}
function timer() {
if (count <= 0) {
clearInterval(counter);
return;
}
else {
counter1 = setInterval(timer1, 10);
}
count = count - 1;
}
答案 4 :(得分:0)
根据之前的回复,我推出了一个vanilla javascript,面向对象的方法。
我还创建了一个github仓库,以防有人想要改进它。
https://github.com/denodster/JSTimer
@JsonSerialize(using = XSerializer.class)
@JsonDeserialize(using = XDeserializer.class)
示例:
function Timer(element){
var interval;
var milliseconds = 0;
var self = this;
function printValue(){
var seconds = Math.round(milliseconds/10)/100;
$(element).empty();
$(element).text(seconds);
}
this.start = function(seconds, countdown){
if(interval){//if an interval exists clear it first
clearInterval(interval);
}
if(seconds) {//if seconds are passed in reset the milliseconds
milliseconds = milliseconds + (seconds * 1000);
}
interval = setInterval(function(){
if(countdown) {
if (milliseconds >= 0) {
milliseconds -= 10;
printValue();
} else {
self.stop();
}
} else {
milliseconds += 10;
printValue();
}
}, 10);
};
this.stop = function(){
clearInterval(interval);
};
this.reset = function(){
milliseconds = 0;
printValue();
};
this.getValue = function(){
return milliseconds/1000;
};
}
答案 5 :(得分:0)
I know this post is old but I thought I should share my answer maybe it will help someone. This script counts the current date/time with milliseconds, minutes, seconds, month, day, year, and suffix, it is easy to modify, you can modify it to countdown if you need to
function showRemaining() {
var currentDate = new Date(); //'11/23/2016 12:00 AM'
var month = currentDate.getMonth() + 1
var day = currentDate.getDate()
var year = currentDate.getFullYear()
var currentTime = new Date()
var hours = currentTime.getHours()
var minutes = currentTime.getMinutes();
var seconds = currentTime.getSeconds();
//var milliseconds = currentTime.getMilliseconds().toString().slice(0, 3); //+ 999; //* 111
var milliseconds = (currentTime.getMilliseconds()/.11).toFixed(0)
//var milliseconds = currentTime * 3
var timer;
if (minutes < 10)
minutes = "0" + minutes
var suffix = "AM";
if (hours >= 12) {
suffix = "PM";
hours = hours - 12;
}
if (hours === 0) {
hours = 12;
}
if (seconds < 10)
seconds = "0" + seconds
if (seconds >= 60) {
seconds = seconds - 60;
}
if (seconds === 60) {
seconds = 60;
}
if (hours < 10)
hours = "0" + hours
if (hours >= 12) {
hours = hours - 12;
}
if (hours === 12) {
hours = 12;
}
if (milliseconds < 1000)
milliseconds = "0000";// + milliseconds
if (milliseconds >= 1000) {
milliseconds = milliseconds - 100; //was 1000
}
if (milliseconds === 1000) {
milliseconds = 1000;
}
var now = new Date();
var distance = currentDate - now;
if (distance < 0) {
return;
}
/*var days = Math.floor(distance / day);
var hours = Math.floor((distance % day) / hour);
var minutes = Math.floor((distance % hours) / minute);
var seconds = Math.floor((distance % minutes) / second);
//var milliseconds = Math.floor(distance % _second) / _millisecond;*/
document.getElementById('countdown').innerHTML = month + '/'; // months
document.getElementById('countdown').innerHTML += day + '/'; // days
document.getElementById('countdown').innerHTML += year + '<br>'; // year
document.getElementById('countdown').innerHTML += hours + ' : '; // hrs
document.getElementById('countdown').innerHTML += minutes + ' : '; // mins
document.getElementById('countdown').innerHTML += seconds + ' : '; // secs
document.getElementById('countdown').innerHTML += milliseconds + ' '; // milliseconds
document.getElementById('countdown').innerHTML += '<b>' + suffix + '</b>'; // suffix
}
timer = setInterval(showRemaining, 1);
<!DOCTYPE html>
<html>
<head>
<script src="https://code.jquery.com/jquery-1.12.4.js"></script>
<meta charset="utf-8">
<meta name="viewport" content="width=device-width">
<title>JS Bin</title>
</head>
<body>
<p id="countdown"></p>
</body>
</html>