var timerElm = document.getElementById("timer");
var startTime = Date.now();
var countDownAmount = 15000; // ms (3603000)
var countDownEnd = startTime + countDownAmount;
var tickAudio = new Audio('https://freesound.org/data/previews/254/254316_4062622-lq.mp3');
var lastSeconds;
function formatTime(hours, minutes, seconds, mseconds) {
hours = String(hours);
minutes = String(minutes);
seconds = String(seconds);
mseconds = String(mseconds);
while (mseconds.length < 3) {
mseconds = "0" + mseconds;
}
seconds = (seconds.length < 2) ? "0" + seconds : seconds;
minutes = (minutes.length < 2) ? "0" + minutes : minutes;
return hours + "h " + minutes + "m " + seconds + "s " + mseconds + "ms";
}
function updateTimer() {
var remainingTime = countDownEnd - Date.now();
var hours = Math.floor(remainingTime / (60 * 60 * 1000));
var minutes = Math.floor(remainingTime / (60 * 1000)) % 60;
var seconds = Math.floor(remainingTime / 1000) % 60;
var mseconds = remainingTime % 1000;
if(lastSeconds && lastSeconds !== seconds && !hours && !minutes && seconds <= 10) {
tickAudio.play();
}
lastSeconds = seconds;
if (remainingTime < 0) {
hours = 0;
minutes = 0;
seconds = 0;
mseconds = 0;
}
else {
requestAnimationFrame(updateTimer);
}
// printout
timerElm.innerHTML = formatTime(hours, minutes, seconds, mseconds);
}
updateTimer();
#timer {
font-size: 32px;
text-align: center;
}
<div id="timer"></div>
我有一个JavaScript计时器,可以在最近10秒内播放声音。
我想让我的用户能够在数分钟内在倒数中添加他们想要的任何数量,添加一个输入字段,以及一个休息,暂停,停止按钮。