javascript - 删除倒数计时器中的 0
问题描述
我创建了一个从 10:00 开始倒计时的倒数计时器,我希望倒数计时器在低于 1 分钟后删除第一个 0。并在其低于 10 秒时包括结尾零。
例如:“0:59”我想删除 0 所以它应该显示“:59”然后“:9”应该显示“:09”
老实说 100%,我没有尝试太多。我想也许这可以用正则表达式来完成,但我不确定如何。
我的计时器:
const mins = 10;
// getting the exact time as of the page load
const now = new Date().getTime();
// the math that is done for the actual countdown. So 10*60*1000 + the time retrieved from the page load.
const deadline = mins * 60 * 1000 + now;
// This is a function, however it is a JavaScript method and calls a function.
setInterval(() => {
// Gets the current time
var currentTime = new Date().getTime();
// gets the 'distance' between the deadline(10 mins) and the current time
var distance = deadline - currentTime;
// found out this method does the math for you, I had to look this up and research it on W3schools
var minutes = Math.floor((distance % (1000 * 60 * 60)) / (1000 * 60));
var seconds = Math.floor((distance % (1000 * 60)) / 1000);
// Inserts the timer into the Span timer
timeSpan.innerHTML = minutes + ':' + seconds;
// the interval is set to 1 sec, so the timer refreshes and counts down every second
if (seconds < 0) {
confirm('Alert For your User!');
window.location.reload();
}
}, 1000);
我没有添加任何开始的方式,因为我不确定从哪里开始!任何帮助都会很棒。
解决方案
:59
您可以使用一些基本的 if 语句(见下文)来做到这一点,但正如评论中的人所说,将其读取而不是读取看起来很奇怪0:59
const timeSpan = document.querySelector('#test');
const mins = 10;
// getting the exact time as of the page load
const now = new Date().getTime();
// the math that is done for the actual countdown. So 10*60*1000 + the time retrieved from the page load.
const deadline = 62 * 1000 + now;
// This is a function, however it is a JavaScript method and calls a function.
setInterval(() => {
// Gets the current time
var currentTime = new Date().getTime();
// gets the 'distance' between the deadline(10 mins) and the current time
var distance = deadline - currentTime;
// found out this method does the math for you, I had to look this up and research it on W3schools
var minutes = Math.floor((distance % (1000 * 60 * 60)) / (1000 * 60));
var seconds = Math.floor((distance % (1000 * 60)) / 1000);
if (minutes > 0) {
if(seconds < 10){
timeSpan.innerHTML = minutes + ':0' + seconds;
} else {
// Inserts the timer into the Span timer
timeSpan.innerHTML = minutes + ':' + seconds;
}
} else if(seconds < 10) {
timeSpan.innerHTML = ':0' + seconds;
} else {
timeSpan.innerHTML = ':' + seconds;
}
// the interval is set to 1 sec, so the timer refreshes and counts down every second
if (seconds < 0) {
confirm('Alert For your User!');
window.location.reload();
}
}, 1000);
<p id="test">
</p>
推荐阅读
- python - 仅在通过 Python 子进程调用时出现 SQL*Loader 错误
- javascript - 只能获取最旧帖子的 answerID 而不是被点击的帖子
- logging - Tableau Server 日志保留期
- python - 某些服务如何在您通话时读取您在拨号盘中键入的内容?
- sql - 在 SQL 中不进行聚合的数据透视
- python - Keras 纪元计数回调是否适用于多个拟合会话?
- google-sheets - 自动从谷歌表格的下拉列表中删除
- windows - 如何使用powershell获取共享文件夹级别权限
- javascript - 通过 selenium Python 复制粘贴?
- path - 获取在 MT4 中使用 ChartApplyTemplate 的路径