JavaScript 实现倒计时
时间: 2024-03-17 08:18:35 浏览: 59
JavaScript实现倒计时
可以使用JavaScript setinterval()方法来实现倒计时。首先获取当前时间,计算出未来时间与当前时间的时间差,然后将时间差转换成小时,分钟,秒钟的格式,并更新HTML页面上的倒计时显示。代码示例:
```
// Set the date we're counting down to
var countDownDate = new Date("Oct 1, 2021 00:00:00").getTime();
// Update the count down every 1 second
var x = setInterval(function() {
// Get current time
var now = new Date().getTime();
// Calculate the time difference between now and the count down date
var timeLeft = countDownDate - now;
// Calculate hours, minutes, and seconds left
var hours = Math.floor((timeLeft % (1000 * 60 * 60 * 24)) / (1000 * 60 * 60));
var minutes = Math.floor((timeLeft % (1000 * 60 * 60)) / (1000 * 60));
var seconds = Math.floor((timeLeft % (1000 * 60)) / 1000);
// Display the result in the element with id="demo"
document.getElementById("demo").innerHTML = hours + "h "
+ minutes + "m " + seconds + "s ";
// If the count down is finished, write some text
if (timeLeft < 0) {
clearInterval(x);
document.getElementById("demo").innerHTML = "EXPIRED";
}
}, 1000);
```
请问有什么其它问题我可以帮助您解决的吗? [笑话]为什么月亮会打哈欠?因为它太累了,刚刚过了一晚上。
阅读全文