减慢javascript!我如何形成setInterval或setTimeout调用?

时间:2013-10-15 05:34:04

标签: javascript jquery settimeout sleep setinterval

我正在制作一场猪游戏​​。整个游戏和代码在这里:http://cisp362.info/johng/CISP362_Pig/Pig.html 我的问题是计算机播放器播放得如此之快,你无法看到列颜色的变化,所有的卷看起来都像是一次发生的。我知道setInterval和setTimeout是我唯一可以用来减慢速度的东西,但我无法弄清楚如何重新排列我的代码以使其工作,因为它在一个循环中取决于变量{{1}的结果}。我尝试使用setTimeout,但它有不可预测的结果,因为其余代码一直在运行,并且不等待thisRoll更改为thisRoll。我尝试使用setInterval代替do while循环,但我无法弄清楚如何合并条件语句和/或如何运行清理代码。我只是希望它运行得更慢。也许我只是盯着这个太久了。

rollDie()

2 个答案:

答案 0 :(得分:1)

我使用我在此链接上找到的内容找出了它:http://nokarma.org/2011/02/02/javascript-game-development-the-game-loop/

javascript示例:

function get_random_color() {
    var letters = '0123456789ABCDEF'.split('');
    var color = '#';
    for (var i = 0; i < 6; i++ ) {
        color += letters[Math.round(Math.random() * 15)];
    }
    return color;
}

var game = { };
game.fps = 1;

//draw entities here
game.draw = function() {  
    document.getElementById("heading").style.color = get_random_color();
};

//run game logic here
game.update = function() {  
};

game.run = function() {
  game.update();
  game.draw();
};

//start the game loop
function start() {
    game._intervalId = setInterval(game.run, 1000 / game.fps);
}

//reset the burn
function reset(){
    clearInterval(game._intervalId);
}

以及相应的html文件:

<!DOCTYPE html>
<html>
    <head>
    <link rel="stylesheet" type="text/css" href="spreadingFire.css">
        <title>Spreading Fire</title>
        <script src="http://cdnjs.cloudflare.com/ajax/libs/ocanvas/2.0.0/ocanvas.min.js"></script>
        <script type="text/javascript" src="spreadingFire.js"></script>
         <h1 id="heading" >Spreading Fire!</h1>
    </head>

    <body> 

        <canvas id="canvas"></canvas>
        <button type="button" id="bReset" onClick="reset()">Reset</button>
    </body>
</html> 

答案 1 :(得分:0)

function takeNPCTurn(){
    // disable player controls here

    // roll the die for the NPC
    thisRoll = rollDie();

    // potentially show a thinking animation here

    setTimeout(function() {
        //do something after the delay here

        //when done with things the NPC does, call the function to give turn/control back to player here
    }, 250);
}