# [JS30] Day.29 Countdown Clock ###### tags: `JS30` ## 任務 Task * 做一個倒計時的功能,可以使用按鈕控制倒數分鐘,也可以自行輸入分鐘數進行倒數。 ==完成時間:30min== ## 步驟 Step 1. 建立一個 `timer()` 傳入倒數的秒數。 2. 將傳入的秒數放入 `displayTimeLeft()` 轉換成分鐘及秒數,渲染到畫面上呈現最一開始的倒數時間,記得小於零的數前面要補零。 3. 設定變數 `then = Date.now() + seconds * 1000` 得出倒計時後的毫秒數。 4. 設定 `setInterval()` 設定每秒時間為 `secondLeft = (then - Date.now()) / 1000` (每秒 Date.now() 都會越來越多逼近 then 的毫秒數,相減就會變成倒計時)。 5. 設定如果 `secondLeft` 小於 0 ,則清除倒計時並回傳,如果大於零則執行 `displayTimeLeft(secondLeft)` 每秒渲染新的倒計時數值。 6. 建立 `displayEndTime()` 傳入倒計時完的秒數,並轉換成小時及分鐘,渲染到畫面呈現倒計時完的時間。 7. 監聽每個按鈕的 `click` 事件,將設定好的 `data-time` 秒數傳入 `timer()` 。 8. 監聽 `input` 的 `submit` 事件,將輸入的分鐘轉為秒數,並傳入 `timer()`。 ## 筆記 Note ### <font color=#337EA9>CSS focus</font> * 表示獲得聚焦的元素,當點擊、觸摸元素或通過 `Tab` 鍵選擇時被觸發。 ### <font color=#337EA9>JS Date.now()</font> * 可取得當前時間,ES5 才出現。 * 以前的取得方式為 `new.Date().getTime()` 。 ### <font color=#337EA9>JS name</font> * 可直接選取節點。 ```htmlembedded= <body> <form name = 'myForm'> <input name = 'minutes'> </form> </body> ``` ```javascript= console.log( document.customForm == document.querySelector("[name = 'customForm']") ); //output: true ``` ## 遇到問題 Problem :::danger ⚠️ <font color=black>Problem</font> ::: * 輸入文字會跑出 `NaN`。 :::info :ok_hand: <font color=black>Revise</font> ::: * 判斷 `isNaN` 如果是則跳出警告,且清空欄位。 ```javascript= document.customForm.addEventListener("submit", function (e) { e.preventDefault(); if (isNaN(this.minutes.value)) { alert("enter the number"); this.reset(); return; } displayTime(this.minutes.value * 60); this.reset(); }); ``` ## 想法 Idea :::warning :bulb: <font color=black> 做一個正計時且可以設定迴圈。 </font> ::: <iframe height="300" style="width: 100%;" scrolling="no" title="Untitled" src="https://codepen.io/jim876633/embed/BarzYxp?default-tab=" frameborder="no" loading="lazy" allowtransparency="true" allowfullscreen="true"> See the Pen <a href="https://codepen.io/jim876633/pen/BarzYxp"> Untitled</a> by Jim (<a href="https://codepen.io/jim876633">@jim876633</a>) on <a href="https://codepen.io">CodePen</a>. </iframe> ### 方法 method