代码块中的代码未按顺序执行

发布于 2025-01-31 03:47:05 字数 409 浏览 1 评论 0原文

请帮助刚刚开始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 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(1

冷清清 2025-02-07 03:47:05

重新启动可能是 首先被调用。您可以使用 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 using console.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 the alert 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.

~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文