JavaScript计数计时器

时间:2017-09-14 13:24:04

标签: javascript html count

我想添加将从指定时间开始计数的计时计时器。 我想这样做如下: 我会添加按钮" reset"点击之后,计时器启动并从指定的时间开始计时,但是如果我将来再次按它,​​它将计算未来指定时间的时间。

var countDownDate = new Date();
// Update the count down every 1 second
var x = setInterval(function() {

  // Get todays date and time
  var now = new Date().getTime();

  // Find the distance between now an the count down date
  var distance = countDownDate.getTime() + now;

  // Time calculations for days, hours, minutes and seconds
  var days = Math.floor(distance / (1000 * 60 * 60 * 24));
  var hours = Math.floor((distance % (1000 * 60 * 60 * 24)) / (1000 * 60 * 60));
  var minutes = Math.floor((distance % (1000 * 60 * 60)) / (1000 * 60));
  var seconds = Math.floor((distance % (1000 * 60)) / 1000);

  // Output the result in an element with id="demo"
  document.getElementById("demo").innerHTML = days + "d " + hours + "h " + minutes + "m " + seconds + "s ";
}, 1000);

我有这样的代码,但输出非常错误。 这是链接:JSFiddle

2 个答案:

答案 0 :(得分:0)

<!doctype html>
	<html>
		<body>
			<button onclick="console.log(getTimeElapsed());">Log Time Elapsed</button>
			<script type="application/javascript">		
				var startTime = Date.now(); // Get Starting time in MS
				var endTime = 0;
				var timeElapsed = 0;

				function getTimeElapsed() {
					endTime = Date.now(); // Get current Time
					timeElapsed = endTime - startTime; // current time - startTime = Time Elapsed
					startTime = Date.now();
					
					return timeElapsed * 0.001; // Convert MS to S
				}
			</script>
		</body>
	</html>

答案 1 :(得分:0)

使用localStorage保存日期

var countDownDate = localStorage.getItem('startDate');
if (countDownDate) {
    countDownDate = new Date(countDownDate);
} else {
    countDownDate = new Date();
    localStorage.setItem('startDate', countDownDate);
}

// Update the count down every 1 second
var x = setInterval(function() {

    // Get todays date and time
    var now = new Date().getTime();

    // Find the distance between now an the count down date
    var distance = now - countDownDate.getTime();

    // Time calculations for days, hours, minutes and seconds
    var days = Math.floor(distance / (1000 * 60 * 60 * 24));
    var hours = Math.floor((distance % (1000 * 60 * 60 * 24)) / (1000 * 60 * 60));
    var minutes = Math.floor((distance % (1000 * 60 * 60)) / (1000 * 60));
    var seconds = Math.floor((distance % (1000 * 60)) / 1000);

    // Output the result in an element with id="demo"
    document.getElementById("demo").innerHTML = days + "d " + hours + "h " + minutes + "m " + seconds + "s ";
}, 1000);

https://jsfiddle.net/5a6ranep/1/