JavaScript定時函數(2)setInterval與clearInterval

setInterval的使用方法 javascript

<!DOCTYPE html>
<html lang="en">
<head>
  <meta charset="UTF-8">
  <title>Document</title>
</head>
<body>
  <h3 id="hid">0</h3>
  <script type="text/javascript">
    var hid = document.getElementById("hid");
    var num = 1;
    function myTime(){
      hid.innerHTML = num;
      num++;
    }
    setInterval("myTime()",1000); // setInterval是每隔time毫秒執行一次函數
  </script>
</body>
</html>



clearInterval清除定時效果

<!DOCTYPE html>
<html lang="en">
<head>
  <meta charset="UTF-8">
  <title>Document</title>
</head>
<body>
  <h3 id="hid">0</h3>
  <script type="text/javascript">
    var hid = document.getElementById("hid");
    var num = 1;
    var sid = null; // 存放setInterval
    function myTime(){
      hid.innerHTML = num;
      if(num == 5){
        clearInterval(sid);
      }
      num++;
    }
    sid = setInterval("myTime()",1000); // 存儲起來
  </script>
</body>
</html>



手動中止

<!DOCTYPE html>
<html lang="en">
<head>
  <meta charset="UTF-8">
  <title>Document</title>
</head>
<body>
  <h3 id="hid">0</h3>
  <button onclick="clearInterval(sid)">點擊中止</button>
  <script type="text/javascript">
    var hid = document.getElementById("hid");
    var num = 1;
    var sid = null; // 存放setInterval
    function myTime(){
      hid.innerHTML = num;
      num++;
    }
    sid = setInterval("myTime()",1000); // 存儲起來
  </script>
</body>
</html>



setInterval和setTimeout的區別

  1. setTimeout是隻執行一次,執行屢次的效果是使用了遞歸的方法
  2. setInterval默認就是每隔多長時間執行一次函數,默認就是無限次調用
相關文章
相關標籤/搜索