Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
317 views
in Technique[技术] by (71.8m points)

javascript - I am trying to make a tic-tac-toe game and to do so I have to have solve this:

I am expecting the while loop to stop after I click the button, but my whole screen is frozen, and the window doesn't seem to react to any sort of event.

<!DOCTYPE html>
<html lang="en">

<head>
  <meta charset="UTF-8">
  <meta name="viewport" content="width=device-width, initial-scale=1.0">
  <title>Document</title>
</head>
<body>
  <button>Click ME!</button>
  <script>
    const btn = document.querySelector("button");
    let clicked = false;
    btn.addEventListener("click", ()=>{
        console.log("clicked");
        clicked = true;
    })
    while(!clicked){
        console.log("I am waiting")
    }
  </script>
</body>

</html>
question from:https://stackoverflow.com/questions/65646766/i-am-trying-to-make-a-tic-tac-toe-game-and-to-do-so-i-have-to-have-solve-this

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

Your while loop is running immediately and without a break and will block the code from executing

you likely mean this

const btn = document.querySelector("button");
let clicked = false;
btn.addEventListener("click", () => {
  console.log("clicked");
  clicked = true;
})
let iId = setInterval(function() {
  if (clicked) clearInterval(iId); // clear the interval
  else console.log("I am waiting"); // continue the interval
}, 1000)
<button>Click ME!</button>

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...