html容器
<div id='time'></div>
首先是设置一个容器用来放置计时器,这里比较随意
JS代码实现计时显示
showTime: function () {
var date = new Date();
var year = date.getFullYear();
var month = date.getMonth() + 1;
if (month < 10) month = "0" + month;
var day = date.getDate();
if (day < 10) day = "0" + day;
var hour = date.getHours();
if (hour < 10) hour = "0" + hour;
var minute = date.getMinutes();
if (minute < 10) minute = "0" + minute;
var second = date.getSeconds();
if (second < 10) second = "0" + second;
document.getElementById("time").innerText = year + "-" + month + "-" + day + " " + hour + ":" + minute + ":" + second;
}
使用Date()函数来获取时间节点
Interval循环调用
var interval = setInterval("showTime()", 1000);
第二个参数单位是毫秒
停止调用
clearInterval(interval);