代码块中的代码未按顺序执行
请帮助刚刚开始JS的新手,我在游戏中具有检查错误条件然后重新启动游戏的功能。由于某种原因,restart()函数总是在其他两行之前调用,该函数查询HTML并显示游戏结果。
function checkResult(id) {
if (!combo.includes(id)){
document.querySelector('body').classList.add('game-over');
document.getElementById("title").innerHTML = "You lost, Press start button to restart";
restart();
}
function restart() {
alert("game started")
please help the newbie that just started the js, I have a function in the game that checks for a false condition and then restarts the game. For some reason, the restart() function was always called before the other two lines, that query the HTML and shows the game result.
function checkResult(id) {
if (!combo.includes(id)){
document.querySelector('body').classList.add('game-over');
document.getElementById("title").innerHTML = "You lost, Press start button to restart";
restart();
}
function restart() {
alert("game started")
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(1)
重新启动
可能是 首先被调用。您可以使用 chrome decugging工具 打印出操作顺序。发生的事情是,直到下一个重新粉刷之前,浏览器的DOM更改才由视觉上代表。重新粉刷发生在代码的同步块之间。
重新启动
是同步的,因此在查看DOM更改之前,您会看到警报
。如果您想等待浏览器重新启动,我相信您可以使用
requestAnimationFrame
api(请参阅 so so答案)。这全都假设您的代码缺少括号,这只是复制式纸或错误。请确保您的语法正确。
It's likely that
restart
is not being called first. You can verify this using the chrome debugging tools or usingconsole.log
to print out the order of operations.What's going on is that your DOM changes are not visually represented by the browser until the next repaint. Repainting happens in between synchronous blocks of code.
restart
is synchronous, so you see thealert
before you see the DOM changes.If you want to wait for the browser to repaint, I believe you can make use of the
requestAnimationFrame
API (see this SO answer).This is all assuming that your code missing brackets and such is just a copy-paste error. Do ensure your syntax is correct.