1. 程式人生 > >js 週期性定時器

js 週期性定時器

週期性定時器:設定一個時間間隔,時間一到,做指定的事情,然後重新計時

  • 設定:var timer = setInterval(函式, 時間)

  • 清除:clearInterval(timer)

<html>     <head>         <meta charset="utf-8" />         <title>週期性定時器</title>         <style>             div {                 margin: 100px auto;                 width: 300px;                 height: 200px;                 background: greenyellow;                 color: white;                 font-size: 50px;                 text-align: center;                 line-height: 200px;             }         </style>     </head>     <body>         <div>0</div>     </body>     <script>                  var timer = null         var oDiv = document.getElementsByTagName('div')[0]                  oDiv.onmouseover = function () {             // 先儲存起來,然後再使用             var _this = this             // 建立定時器             timer = setInterval(function(){                 // 定時器任務函式中的this沒有意義                 var num = parseInt(_this.innerText)                 num++                 _this.innerText = num             }, 1000)         }         oDiv.onmouseout = function () {             // 清除定時器             clearInterval(timer)         }              </script> </html>

滑鼠放上面數字自動增加,滑鼠移開停止增加數字。