我可以在setTimeout中预先定义一个函数,所以我不在括号中调用它

时间:2013-10-22 11:25:03

标签: javascript settimeout

我对这种令人难以置信的语言有点新意,我正在尝试创建一个功能,让我慢慢揭示战斗的进展。我可以提前编写我的函数,然后在setTimeout中声明函数而不必重写它,因为它似乎永远不会起作用。这是我做过的不太好的代码:

var health=100;
var ehealth=100;
var atk;
var eatk;

function attack(x){
    x=Math.floor(Math.random()*11);
    atk=x;
    ehealth=ehealth-atk
    document.write('Enemy Health:' + '   ' + ehealth + '   ')
}

function eattack(x){
    x=Math.floor(Math.random()*11);
    eatk=x;
    health=health-eatk
    document.write('Health:' + '   ' + health )
}

function dead(){
    if(health<=0){
        document.write('You Lose');
    }else{
        if(ehealth<=0){
            document.write('You Win');
        }
    }
}

function battle(){
    document.write('Enemy Health:' + '&nbsp; &nbsp;' + ehealth + '&nbsp; &nbsp; Health: &nbsp; &nbsp;' + health + '<br/>\n')
    while(health>=0&&ehealth>=0){
        setTimeout(attack(0),400)
        setTimeout(eattack(0),400)
        document.write("<br/>\n");
        dead();
    }
}

帮助!

1 个答案:

答案 0 :(得分:1)

这样称呼:

setTimeout(function () {
    attack(0);
}, 400);

如果你这样做:

setTimeout(attack(0), 400);

它会立即评估attack(0),它会尝试使用attack(0)的输出作为回调函数(这不是你想要的)。