通过Date()显示时间:使用setInterval()不会更新它

时间:2016-04-28 23:14:21

标签: javascript jquery

我有这段代码用西班牙语显示时间和一些日期信息:

  var date = new Date();

  var hour = date.getHours().toString();
  var minutes = date.getMinutes().toString();

  var day = date.getDate();

  switch (date.getMonth()) {
      case 0:
      month = "Ene";
      break;
      case 1:
      month = "Feb";
      break;
      case 2:
      month = "Mar";
      break;
      case 3:
      month = "Abr";
      break;
      case 4:
      month = "May";
      break;
      case 5:
      month = "Jun";
      break;
      case 6:
      month = "Jul";
      break;
      case 7:
      month = "Ago";
      break;
      case 8:
      month = "Sep";
      break;
      case 9:
      month = "Oct";
      break;
      case 10:
      month = "Nov";
      break;
      case 11:
      month = "Dic";
      break;
  } 

  if (hour.length == 1) { 
    hour = '0' + hour;
  }
  if (minutes.length == 1) { 
    minutes = '0' + minutes;
  }
  setInterval($('#hour').html('<b>' + hour + ':' + minutes + '<br>' + '<span class="day">' + day + ' ' + month + '</span></b>'), 60000);

当我加载文档时,它可以正常工作。问题的时间永远不会被破坏......为什么?

1 个答案:

答案 0 :(得分:2)

正如@Travis J指出的那样,setTimeout第一个参数应该是一个函数。 (见the doc。)

在您的情况下,您还希望此函数在每次调用时重新计算日期。

类似于:

// Define a function that will update the html from current date
function updateDate() {
  var date = new Date();

  var hour = date.getHours().toString();
  var minutes = date.getMinutes().toString();

  var day = date.getDate();

  switch (date.getMonth()) {
      case 0:
      month = "Ene";
      break;
  ...
  }

  if (hour.length == 1) { 
    hour = '0' + hour;
  }
  if (minutes.length == 1) { 
    minutes = '0' + minutes;
  }

  // Update the page content
  $('#hour').html('<b>' + hour + ':' + minutes + '<br>' + '<span class="day">' + day + ' ' + month + '</span></b>' 
}

// Call the function the first time (setInterval will not call it right away)
updateDate();

// Schedule the function to be called every minute after that
setInterval(updateDate, 60000);