文章内容

2023/7/10 20:20:23,作 者: 黄兵

JavaScript 实现倒计时效果

下面的代码使用 JavaScript 实现了一个倒计时的效果:

<!DOCTYPE html>
<html>
<head>
<title>10分钟倒计时</title>
</head>
<body>
<h1 id="countdown">10:00</h1>

<script>
// 获取倒计时显示元素
const countdownElement = document.getElementById('countdown');

// 设置倒计时时间为10分钟(以秒为单位)
let timeLeft = 10 * 60;

// 更新倒计时显示
function updateCountdown() {
const minutes = Math.floor(timeLeft / 60);
const seconds = timeLeft % 60;

// 在倒计时显示元素中更新时间
countdownElement.textContent = `${minutes.toString().padStart(2, '0')}:${seconds.toString().padStart(2, '0')}`;

// 减少剩余时间
timeLeft--;

// 当倒计时结束时,停止更新
if (timeLeft < 0) {
clearInterval(countdownTimer);
countdownElement.textContent = "倒计时结束";
}
}

// 每秒更新一次倒计时显示
const countdownTimer = setInterval(updateCountdown, 1000);
</script>
</body>
</html>

上述代码实现了一个显示 10 分钟倒计时的效果。

页面上会显示一个标题为 "10分钟倒计时" 的大标题,下方是一个显示倒计时时间的元素。每秒钟,倒计时时间都会更新,直到倒计时结束。


其它相关推荐:

1、JavaScript中&&理解

2、图解Javascript上下文与作用域

3、javascript逻辑运算符“||”和“&&”

4、Javascript 一致/严格相等 (===)与相等(==)

5、Javascript闭包

分享到:

发表评论

评论列表