🙂
JavaScript - 程式設計
  • JavaScript - 程式設計
  • 1. 簡介
    • 1.1 講者簡介
    • 1.2 課程簡介
    • 1.3 開發工具簡介
    • 1.4 第一個 JavaScript
  • 2. 網站技術簡介
    • 2.1 網站前端技術
    • 2.2 網站後端技術
    • 2.3 JavaScript 簡介
  • 3. JavaScript程式語言
    • 3.1 套用 JavaScript
    • 3.2 註解(Comment)
    • 3.3 變數(Variable)
    • 3.4 資料型態(Data Types)
    • 3.5 Strict 模式
    • 3.6 運算子(Operator)
    • 3.7 字串(String)
    • 3.8 數值(Number)
    • 3.9 陣列(Array)
    • 3.10 物件(Object)
    • 3.11 條件式(Conditional)
    • 3.12 迴圈(Loop)
    • 3.13 函式(Function)
    • 3.14 類別(Class)
    • 3.15 傳值呼叫、傳址呼叫
    • 3.16 變數可視範圍(scope)
    • 3.17 錯誤補捉(Errors)
    • 3.18 資料格式
  • 4. JavaScript常用函式及主題
    • 4.1 JSON
    • 4.2 時間間隔執行
    • 4.3 數學(Math)
    • 4.4 日期時間(Date)
    • 4.5 陣列迭代(Iteration)
    • 4.6 陣列排序(Sort)
    • 4.7 正規表達式(Regular Expression)
    • 4.8 效能測試
    • 4.9 this 關鍵字
  • 5. 參考資料
Powered by GitBook
On this page
  • setTimeout()
  • setInterval()、clearInterval()
  1. 4. JavaScript常用函式及主題

4.2 時間間隔執行

在 javascript/practice 資料夾下,建立 time_period.html 來練習。

setTimeout()

隔指定的毫秒數,然後指定第一個函式參數裡的程式:

寫法一:

console.log("程式一");
console.log("程式二");
console.log("程式三");

setTimeout(function(){
  console.log("程式四");
  console.log("程式五");
}, 5000); // 5 秒之後,執行第一個函式參數裡的程式。

console.log("這裡的程式");

寫法二:

console.log("程式一");
console.log("程式二");
console.log("程式三");

function other_func(){
  console.log("程式四");
  console.log("程式五");
}

setTimeout(function(){
  other_func();
}, 5000);

setInterval()、clearInterval()

每隔幾秒,就執行某段程式。

例 1:每隔三秒,就執行函式裡的程式:

setInterval(function(){
  console.log("執行");
}, 3000);

例 2:回傳 id:

var interval_id = setInterval(function(){
  console.log("執行");
}, 3000);
console.log(interval_id);

如果要讓 setInterval() 的停止執行的話,就找時機點執行:

clearInterval(interval_id);

例 3:試著執行以下並解讀:

var i = 0;

var interval_id = setInterval(function(){
  
  console.log("執行");
  i++;
  if(i == 5){
    clearInterval(interval_id);
    console.log("停止執行");
  }
  
}, 3000);

console.log("interval 的 id:" + interval_id);

Previous4.1 JSONNext4.3 數學(Math)

Last updated 4 years ago