我正在尝试制作井字游戏,为此我必须解决这个问题:
I am trying to make a tic-tac-toe game and to do so I have to have solve this:
我希望 while 循环在单击按钮后停止,但我的整个屏幕都冻结了,window 似乎对任何事件都没有反应。
<!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>
那是因为你的代码添加了一个事件侦听器(稍后),然后有一个等待 clicked
的循环,但它实际上会阻止 addEventListener
的执行。虽然有代码 运行 (就像你的循环)你(作为用户)甚至不能点击页面,即使你可以, addEventListener
回调也会在循环结束后执行。所以这是一种僵局。
我建议您阅读 Event loop,这是 JavaScript 运行时的主要机制,以便更好地理解这一点。
您的 while 循环 运行 立即且没有中断,将阻止代码执行
你可能是这个意思
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>
我希望 while 循环在单击按钮后停止,但我的整个屏幕都冻结了,window 似乎对任何事件都没有反应。
<!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>
那是因为你的代码添加了一个事件侦听器(稍后),然后有一个等待 clicked
的循环,但它实际上会阻止 addEventListener
的执行。虽然有代码 运行 (就像你的循环)你(作为用户)甚至不能点击页面,即使你可以, addEventListener
回调也会在循环结束后执行。所以这是一种僵局。
我建议您阅读 Event loop,这是 JavaScript 运行时的主要机制,以便更好地理解这一点。
您的 while 循环 运行 立即且没有中断,将阻止代码执行
你可能是这个意思
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>