代码未 运行 在 javascript 中同步

Code not running synchronized in javascript

我是 javascript 编程的新手。我多年来一直在使用 C++/JAVA/Python 等经典语言工作,但我找不到一种方法来理解代码在 javascript 中被分配为 运行 的方式。

我想在 javascript 中制作俄罗斯方块游戏,因为我有更多的设计优势。

部分代码如下所示:

function output(){
    for(var i=0;i<14;i++)
    {
        for(var j=0;j<12;j++){
            if(game[i][j]==0)
                table.rows[i].cells[j].style.backgroundColor = "black";
            if(game[i][j]==1) // rosu line
                table.rows[i].cells[j].style.backgroundColor = "red";
            if(game[i][j]==2) // galben square
                table.rows[i].cells[j].style.backgroundColor = "yellow";
            if(game[i][j]==3) // verde lshape
                table.rows[i].cells[j].style.backgroundColor = "green";
            if(game[i][j]==4) // albastru jshape
                table.rows[i].cells[j].style.backgroundColor = "blue";
            if(game[i][j]==5) // cyan tee
                table.rows[i].cells[j].style.backgroundColor = "violet";
            if(game[i][j]==6) // violet zshape
                table.rows[i].cells[j].style.backgroundColor = "cyan";
            if(game[i][j]==7) // orange lshape
                table.rows[i].cells[j].style.backgroundColor = "orange";
        }
    }
}
var rand;
function create(){
    rand = Math.floor(Math.random() * 7);
    if(rand == 0)
        stack = line;
   if(rand == 1)
        stack = square;
    if(rand == 2)
        stack = lshape;
    if(rand == 3)
        stack = jshape;
    if(rand == 4)
        stack = tee;
    if(rand == 5)
        stack = zshape;
    if(rand == 6)
        stack = lshape;
    rand++;
    for(i=0;i<=3;i++)
        for(j=0;j<=3;j++)
            {
                if(game[i][j+5] != 0)
                    game_over = 1;
            }
    for(var i=0;i<4;i++)
    {
        for(var j=0;j<4;j++)
            {
                game[i][j+5] = stack[i][j]*rand;
            }
    }
    ci = 0;
    cj = 5;

    piesa_ok = 1;
}
function main(){
    while(good_piece)
    {
        create(); // it contains a statement that modifies the good_piece variable
        output(); // changes some lines from a table in html
    } 
    if(!good_piece)
        alert("game over!");
}

以下代码显示游戏结束警报,然后显示修改后的 table 我使用输出函数更改。我需要做什么才能获得按编写顺序逐行运行的代码?

PS : main 作为 onclick 事件运行:

<button id="start_game" type="submit" style="text-align: center" onclick="main();">CLICK TO START THE GAME</button>

Javascript 环境是单线程的。您编写的每个代码片段都无需执行额外操作(如 setTimeOut 或 setInterval),就可以在 ui 线程上运行。您在该代码中所做的是阻塞 ui 线程。您的代码按编写顺序运行,但您在代码完成后看到 ui 更改,因为它被阻止了。

JavaScript 运行 在浏览器中是单线程的,所以你写的代码确实按照你期望的顺序执行。但是,页面更新不是同步完成的,而警报调用是同步的。

这意味着当浏览器执行您的 output 方法时,它会在内部更新 DOM 并且可能设置某种脏标志告诉浏览器它需要更新页面,但它没有实际上并不是同步进行的。它将等到您的 JavaScript 代码完成(在您的 alert 调用之后),然后执行返回到浏览器内置的事件循环。然后它会实际更新页面。

我认为您的困惑源于浏览器作为事件循环运行的事实:您只需处理事件,对 DOM 进行更新,然后 return 尽快执行浏览器可以保持用户体验流畅。没有 main 并且您不希望其中出现无限循环。