javascript - 单击开始按钮时的 JavaScript 倒数计时器,用于小时、分钟和秒
问题描述
我想在单击按钮时为小时、分钟和秒创建倒数计时器。到目前为止,这是我的代码。
HTML代码
<div class="colomn" style="margin-right: 20px">
<button class="start" onclick="clock();">Start</button>
</div>
javascript函数
<script>
var myTimer;
function clock() {
myTimer = setInterval(myClock, 1000);
var c = 5;
function myClock() {
document.getElementById("demo").innerHTML = --c;
if (c == 0) {
clearInterval(myTimer);
}
}
}
</script>
这很简单,不显示单独的小时、分钟和秒。我如何将其应用于计数小时、分钟和秒。请帮我。
解决方案
工作代码:
<!DOCTYPE HTML>
<html>
<body>
<p id="demo"></p>
<button onclick="countdownTimeStart()">Start Timer</button>
<script>
// Set the date we're counting down to
function countdownTimeStart(){
var countDownDate = new Date("Sep 25, 2025 15:00:00").getTime();
// Update the count down every 1 second
var x = setInterval(function() {
// Get todays date and time
var now = new Date().getTime();
// Find the distance between now an the count down date
var distance = countDownDate - now;
// Time calculations for days, hours, minutes and seconds
var hours = Math.floor((distance % (1000 * 60 * 60 * 24)) / (1000 * 60 * 60));
var minutes = Math.floor((distance % (1000 * 60 * 60)) / (1000 * 60));
var seconds = Math.floor((distance % (1000 * 60)) / 1000);
// Output the result in an element with id="demo"
document.getElementById("demo").innerHTML = hours + "h "
+ minutes + "m " + seconds + "s ";
// If the count down is over, write some text
if (distance < 0) {
clearInterval(x);
document.getElementById("demo").innerHTML = "EXPIRED";
}
}, 1000);
}
</script>
</body>
</html>
推荐阅读
- angular - Angular PWA 从服务工作者缓存中排除清单
- php - 通过 Google Sheets API (PHP) 插入大型数组
- php - 如何在 Mysql 语句中包含 PHP 变量
- reactjs - 为什么它给我一个钩子警告,而我没有在我的组件中使用任何钩子?
- python - Flask 在显示输出之前显示输出 html 标题
- angular - 在容器中部署 Angular 应用程序无法运行 ng 命令
- php - 提交表单PHP后如何清除内存
- r - 将日期列格式化为r中数据框中的行编号(左侧)列
- asp.net-core - 如何将模型绑定到具有结果过滤功能的下拉列表输入?
- python - 如何加入 pandas 系列数字使其成为一个数字