SetTimeout正在返回错误的值

时间:2015-12-10 10:23:09

标签: javascript

function updateTime() {
  var currentDate = new Date()
  var day = currentDate.getDate()
  var month = currentDate.getMonth() + 1
  var year = currentDate.getFullYear()
  var d = day + "-" + month + "-" + year;
  var hours = currentDate.getHours() < 10 ? "0" + currentDate.getHours() : currentDate.getHours();
  var minutes = currentDate.getMinutes() < 10 ? "0" + currentDate.getMinutes() : currentDate.getMinutes();
  var seconds = currentDate.getSeconds() < 10 ? "0" + currentDate.getSeconds() : currentDate.getSeconds();
  var t = hours + " " + minutes + " " + seconds;
  var x = d + " " + t;
  return x;
}
console.log(updateTime());
var timerId = setTimeout(updateTime(), 1000);
alert(timerId);

我试图做一个javascript计时器。这里UpdateTime函数正常工作。它恢复了确切的结果。但时间不断显示。它应该根据系统时间而改变。因此我使用setTimeout函数。但它没有回归适当的价值。有人可以帮帮我吗?

3 个答案:

答案 0 :(得分:0)

您应该从setTimeout的回调函数

中删除alert和()

您的代码应为

function updateTime() {
  var currentDate = new Date()
  var day = currentDate.getDate()
  var month = currentDate.getMonth() + 1
  var year = currentDate.getFullYear()
  var d = day + "-" + month + "-" + year;
  var hours = currentDate.getHours() < 10 ? "0" + currentDate.getHours() : currentDate.getHours();
  var minutes = currentDate.getMinutes() < 10 ? "0" + currentDate.getMinutes() : currentDate.getMinutes();
  var seconds = currentDate.getSeconds() < 10 ? "0" + currentDate.getSeconds() : currentDate.getSeconds();
  var t = hours + " " + minutes + " " + seconds;
  var x = d + " " + t;
  return x;
}

setTimeout(updateTime, 1000);

答案 1 :(得分:0)

带有当前日期的javascript计时器

   <!DOCTYPE html>
    <html>
    <body>


    <p id="demo"></p>

    <script>
    var myVar = setInterval(myTimer ,1000);
    function myTimer() {
        var d = new Date();
        document.getElementById("demo").innerHTML = d.toLocaleTimeString();
    }
    </script>

    </body>
    </html>
你会做什么?

答案 2 :(得分:0)

我只是编辑你的代码希望它能帮到你

    function updateTime() {
  var currentDate = new Date()
  var day = currentDate.getDate()
  var month = currentDate.getMonth() + 1
  var year = currentDate.getFullYear()
  var d = day + "-" + month + "-" + year;
  var hours = currentDate.getHours() < 10 ? "0" + currentDate.getHours() : currentDate.getHours();
  var minutes = currentDate.getMinutes() < 10 ? "0" + currentDate.getMinutes() : currentDate.getMinutes();
  var seconds = currentDate.getSeconds() < 10 ? "0" + currentDate.getSeconds() : currentDate.getSeconds();
  var t = hours + " " + minutes + " " + seconds;
  var x = d + " " + t;
  alert(x);/*display time */
}

setTimeout(updateTime, 1000);/* just remove () braces from your code */