英文:
How do I restart countdown timer to 120 seconds every time a new user lands on the page?
问题
<style>
#countdown {
font-size: 36px;
font-weight: bold;
color: white;
text-align: center;
margin: 20px 0;
}
</style>
<p id="countdown"></p>
<script>
function updateCountdown() {
let startTime = new Date("2023-02-28T15:22:00");
const currentTime = new Date();
let diffTime = startTime - currentTime;
let totalSeconds = diffTime / 1000;
while (totalSeconds <= 0) {
startTime.setDate(startTime.getDate() + 7);
diffTime = startTime - currentTime;
totalSeconds = diffTime / 1000;
}
const days = Math.floor(totalSeconds / (24 * 60 * 60));
const hours = Math.floor((totalSeconds % (24 * 60 * 60)) / (60 * 60));
const minutes = Math.floor((totalSeconds % (60 * 60)) / 60);
const seconds = Math.floor(totalSeconds % 60);
document.getElementById("countdown").innerHTML = `${days}d ${hours}h ${minutes}m ${seconds}s`;
}
setInterval(updateCountdown, 1000);
</script>
英文:
I am trying to use this snippet to refresh a countdown timer to 120 seconds when a new user lands on the page. Any help is appreciated.
I am having trouble on two things: how to set the start date to the current time and then to have this countdown from 120 seconds vs. 7 days.
<style>
#countdown {
font-size: 36px;
font-weight: bold;
color: white;
text-align: center;
margin: 20px 0;
}
</style>
<p id="countdown"></p>
<script>
function updateCountdown() {
let startTime = new Date("2023-02-28T15:22:00");
const currentTime = new Date();
let diffTime = startTime - currentTime;
let totalSeconds = diffTime / 1000;
while (totalSeconds <= 0) {
startTime.setDate(startTime.getDate() + 7);
diffTime = startTime - currentTime;
totalSeconds = diffTime / 1000;
}
const days = Math.floor(totalSeconds / (24 * 60 * 60));
const hours = Math.floor((totalSeconds % (24 * 60 * 60)) / (60 * 60));
const minutes = Math.floor((totalSeconds % (60 * 60)) / 60);
const seconds = Math.floor(totalSeconds % 60);
document.getElementById("countdown").innerHTML = `${days}d ${hours}h ${minutes}m ${seconds}s`;
}
setInterval(updateCountdown, 1000);
</script>
答案1
得分: 0
你可以使用
document.addEventListener('DOMContentLoaded', function() {
// 重置计时器
});
像这样
英文:
You can use
document.addEventListener('DOMContentLoaded', function() {
// reset timer
});
like this
通过集体智慧和协作来改善编程学习和解决问题的方式。致力于成为全球开发者共同参与的知识库,让每个人都能够通过互相帮助和分享经验来进步。
评论