JS中添加while/for循环后背景不显示、prompt弹窗无响应如何解决
问题根本原因
JavaScript是单线程执行模型,所有同步任务会在主线程按顺序执行,异步任务(比如你用的setTimeout回调、DOM渲染、弹窗触发逻辑)必须等当前所有同步代码执行完毕后才会进入执行队列等待调用。
你的while循环是同步执行的:
- 初始
replay值为yes,循环会持续触发 - 每次循环只会往异步队列里新增一个
setTimeout任务,但永远不会执行到setTimeout内部修改replay值的逻辑 - 死循环会持续占用主线程,导致DOM渲染、弹窗触发都被阻塞,所以你看不到背景变化也看不到prompt提示框。
修复方案
把循环逻辑改成递归执行异步逻辑的写法,示例代码如下:
//score var score = 0 //name of each gen 1 pokemon var pname = ['#'] //images for each one var bg = ['#'] // 封装单轮游戏逻辑 function runGame() { const num = Math.floor(Math.random() * bg.length) const background = bg[num] document.body.style.backgroundImage = 'url(' + background + ')' setTimeout(() => { const answer = prompt("What pokemon is this?") if (answer?.toLowerCase() == pname[num].toLowerCase()) { alert("correct") score ++ } else { alert("incorrect") } const replay = prompt("Want to keep playing?") // 用户选择继续的话递归调用下一轮 if (replay?.toLowerCase() === 'yes') { runGame() } }, 2000) } // 启动第一轮游戏 runGame()
内容的提问来源于stack exchange,提问作者Sprat
相关产品推荐
相关产品推荐

