首页 > 解决方案 > Javascript Timer 过期后向前运行

问题描述

首先,我必须道歉,因为我不熟悉 Javascript。我从别人那里找到了一个 JS Fiddle,并以某种方式修改了代码。现在我有3个问题。

  1. 如何让手表在过期后继续运行?然后它应该显示 Runs since "0 days 3 hours 2 minutes 20 seconds"。我只关心时间还在继续。我可以自己调整文本。

  2. 始终显示两位数。所以02分01秒

  3. 我只是将时间转移到跨度#hours / #days / #seconds。我怎样才能上课而不是身份证?

我的自定义代码:

CountDownTimer('12/23/2019 0:00 AM');

function CountDownTimer(date) {
     var end = new Date(date);

     var _second = 1000;
     var _minute = _second * 60;
     var _hour = _minute * 60;
     var _day = _hour * 24;
     var timer;

     function showRemaining() {
         var now = new Date();
         var distance = end - now;
         if (distance < 0) {

             clearInterval(timer);

         /* I Know, that i have no (id), because i have not declared it. 
            But i dont wanna have a text with "expired". 
            The timer should count  till ✓ Check! 
            and after reached the date -> 
            count since: 0 day, 0 hours 10 Minuten 30 Sekunden.  */

             document.getElementById(id).innerHTML = 'EXPIRED!';

             return;
         }
         var days = Math.floor(distance / _day);
         var hours = Math.floor((distance % _day) / _hour);
         var minutes = Math.floor((distance % _hour) / _minute);
         var seconds = Math.floor((distance % _minute) / _second);

         document.getElementById("days").innerHTML = days; 
         document.getElementById("hours").innerHTML = hours; 
         document.getElementById("minutes").innerHTML = minutes; 
         document.getElementById("seconds").innerHTML = seconds; 
     }

     timer = setInterval(showRemaining, 1000);
 }
#clockdiv{
	font-family: sans-serif;
	color: #fff;
	font-weight: 100;
	text-align: center;
    margin-top: 50px;
	font-size: 30px;
}

#clockdiv > div{
	padding: 10px;
	border-radius: 3px;
	background: #00BF96;
	display: inline-block;
}

#clockdiv div > span{
	padding: 15px;
	border-radius: 3px;
	background: #00816A;
	display: inline-block;
}

.smalltext{
	padding-top: 5px;
	font-size: 16px;
}
  <div id="clockdiv"><div>
   <span id="days"></span>
    <div class="smalltext">Tage</div>
  </div>
  <div>
    <span id="hours"></span>
    <div class="smalltext">Stunden</div>
  </div>
  <div>
    <span id="minutes"></span>
    <div class="smalltext">Minuten</div>
  </div>
  <div>
    <span id="seconds"></span>
    <div class="smalltext">Sekunden</div>
  </div></div>

我的小提琴:https ://jsfiddle.net/jxdumk39/3/

太感谢了!

标签: javascripthtml

解决方案


答案:

  1. CountDownTimer()递归调用。

改变:

clearInterval(timer);
document.getElementById(id).innerHTML = 'EXPIRED!';

至:

clearInterval(timer);
CountDownTimer(...);
  1. 将 Number 类型转换为字符串并在需要时添加前导零:

改变:

 var days = Math.floor(distance / _day);

至:

var temp = Math.floor(distance / _day);
var days = (temp.toString().length === 1)? '0' + temp : temp;
  1. 您的解决方案没有任何问题。

推荐阅读