Javascript超时函数值未递增

时间:2017-03-10 07:34:09

标签: javascript html setinterval

我正在尝试使用setInterval函数实现javascript超时功能,当我使用该函数时,我能够显示时间,计时器正在递减,但每次我必须为每个重新加载页面迭代。

timer.html

function countTimer(countDownDate) {

  var now = new Date().getTime();

  // Find the distance between now an the count down date
  var distance = countDownDate - 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 ";

  // If the count down is over, write some text
  if (distance < 0) {
    clearInterval(x);
    document.getElementById("demo").innerHTML = "EXPIRED";
  }

}

var countDownDate = new Date("Mar 12, 2017 15:37:25").getTime();

var x = countTimer(countDownDate)

var y = setInterval(x, 1000);
p {
  text-align: center;
  font-size: 60px;
}
<p id="demo"></p>

输出:

  

2d 2h 45m 37s

任何帮助将不胜感激...... :)先谢谢

1 个答案:

答案 0 :(得分:0)

你没有正确使用setInterval,它接受​​字符串文字代码或在设定的延迟后执行的功能。

现在您将 undefined 传递给它。将您的代码更改为

static int height(Node root) {
    if (root == null) {       
        return 0;
    }

    if (root.left == null && root.right==null) {      
        return 1;            
    } else
        // I want to return height - 1.
        // For example if max height is 10, I wanted to return 9.
        return (1 + Math.max(height(root.left), height(root.right));   
    }
}

&#13;
&#13;
var y = setInterval(function () {
    var countDownDate = new Date("Mar 12, 2017 15:37:25").getTime();
    var x = countTimer(countDownDate)
}, 1000);
&#13;
function countTimer(countDownDate) {
  var now = new Date().getTime();
  // Find the distance between now an the count down date
  var distance = countDownDate - 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 ";

  // If the count down is over, write some text
  if (distance < 0) {
    clearInterval(x);
    document.getElementById("demo").innerHTML = "EXPIRED";
  }

}

var y = setInterval(function() {
  var countDownDate = new Date("Mar 12, 2017 15:37:25").getTime();
  var x = countTimer(countDownDate)
}, 1000);
&#13;
p {
  text-align: center;
  font-size: 60px;
}
&#13;
&#13;
&#13;