JS计时函数Demo

<html>
<head>
<title>javaScript 测试</title>
<script type="text/javascript">
var MAX_IDIOT_SECONDS = 10;  //最大发呆时间(秒)

function _fomatDate(dt) {
 var str = dt.getFullYear()
  + '-' + (dt.getMonth() + 1)
  + '-' + dt.getDate()
  + ' ' + dt.getHours()
  + ':' + dt.getMinutes()
  + ':' + dt.getSeconds()
  ;
 return str.replace(/(\b)([1-9])(\b|$)/, '$10$2$3');
}

function _startCount() {
 var dtStart = new Date();
 var objSeconds = document.getElementById('seconds');
 document.getElementById('start').innerHTML = _fomatDate(dtStart);
 objSeconds.innerHTML = '';
 document.getElementById('stop').innerHTML = '';
 var timer = setInterval(function() {
  var dtNow = new Date();
  var seconds = Math.round((dtNow.getTime() - dtStart.getTime()) / 1000);
  objSeconds.innerHTML = seconds;
  if(seconds > MAX_IDIOT_SECONDS) {
   document.getElementById('stop').innerHTML = _fomatDate(dtNow);
   clearInterval(timer);
  }
 }, 1000);
}

var _onMoveEnd = function() {
 var execTimer;
 return function(e) {
  if (execTimer) {
   clearTimeout(execTimer);
  }
  execTimer = setTimeout(function() {
   _startCount();
  }, 200);
 };
}();


window.onload = _startCount;
document.onmousemove = _onMoveEnd;

</script>
</head>
<body >
开始时间:<span id="start"></span>
<br/>
经过时间(秒):<span id="seconds"></span>
<br/>
停止时间:<span id="stop"></span>
</body>
</html>

图形:

 

原文地址:https://www.cnblogs.com/Leo_wl/p/1732626.html