首页 > 解决方案 > 删除倒数计时器中的 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);

我没有添加任何开始的方式,因为我不确定从哪里开始!任何帮助都会很棒。

标签: javascriptcountdowntimer

解决方案


: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>


推荐阅读