javascriptのコードの
「if (timeLeft === 0) 」
だとどうしてタイマーが止まらないのか、そして
「if (timeLeft < 0) 」
だと止まるのか、違いがよく分かりません
詳しい方教えて頂けないでしょうか?
html
1<!DOCTYPE html> 2<html lang="ja"> 3<head> 4 <meta charset="utf-8"> 5 <title>Typing Game</title> 6 <link rel="stylesheet" href="css/styles.css"> 7</head> 8<body> 9 <p id="target">click to start</p> 10 <p class="info"> 11 Letter count: <span id="score">0</span>, 12 Miss count: <span id="miss">0</span>, 13 Time left: <span id="timer">0.00</span> 14 </p> 15 16 <script src="js/main.js"></script> 17</body> 18</html>
javasctipt
1'use strict'; 2 3{ 4 const words = [ 5 'apple', 6 'sky', 7 'blue', 8 'middle', 9 'set', 10 ]; 11 let word = words[Math.floor(Math.random() * words.length)]; 12 let loc = 0; 13 let score = 0; 14 let miss = 0; 15 const timeLimit = 3 * 1000; 16 let startTime; 17 18 const target = document.getElementById('target'); 19 const scoreLabel = document.getElementById('score'); 20 const missLabel = document.getElementById('miss'); 21 const timerLabel = document.getElementById('timer'); 22 23 function updateTarget() { 24 let placeholder = ''; 25 for (let i = 0; i < loc; i++) { 26 placeholder += '_'; 27 } 28 target.textContent = placeholder + word.substring(loc); 29 } 30 31 function updateTimer() { 32 const timeLeft = startTime + timeLimit - Date.now(); 33 timerLabel.textContent = (timeLeft / 1000).toFixed(2); 34 35 36const timerId = setTimeout(updateTimer, 10); 37 38 39if (timeLeft === 0) { 40 clearTimeout(timerId); 41 alert('Game over'); 42} 43 44 45} 46 47 window.addEventListener('click', () => { 48 target.textContent = word; 49 startTime = Date.now(); 50 updateTimer(); 51 52 }); 53 54 window.addEventListener('keydown', e => { 55 if (e.key === word[loc]) { 56 loc++; 57 if (loc === word.length) { 58 word = words[Math.floor(Math.random() * words.length)]; 59 loc = 0; 60 } 61 updateTarget(); 62 score++; 63 scoreLabel.textContent = score; 64 } else { 65 miss++; 66 missLabel.textContent = miss; 67 } 68 }); 69} 70
回答3件
あなたの回答
tips
プレビュー