Javascript计时器过期后向前运行

时间:2018-11-19 00:20:56

标签: javascript html

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

  1. 如何让手表在过期后继续运行?然后应显示“从0天3小时2分20秒开始运行”。我只关心时间在继续。我可以自己修改文字。

  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/

非常感谢您!

1 个答案:

答案 0 :(得分:0)

答案:

  1. 递归调用CountDownTimer()

更改:

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

收件人:

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

更改:

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

收件人:

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