简体   繁体   English

setTimeout()方法将不会执行

[英]setTimeout() method won't execute

I have written a script, but i want to limit execution time for some functions. 我已经写了一个脚本,但是我想限制某些功能的执行时间。 I decided to try setTimeout() method, however it results in no time out when i execute the program, ie setTimeout() does not work. 我决定尝试setTimeout()方法,但是当我执行程序时,它不会导致超时,即setTimeout()不起作用。

setTimeout(rollDice(), 6000) is the line that executes instantly setTimeout(rollDice(),6000)是立即执行的行

Here is my code : 这是我的代码:

function rollDice() {
diceOne = Math.round(5 * Math.random() + 1);
diceTwo = Math.round(5 * Math.random() + 1);
}
function mainFunction() {
playerAI.playing = true;
playerOne.playing = true;
currentScore = 0;
playerAI.totalScore = 0;
playerOne.totalScore = 0;
while (playerAI.playing == true && playerOne.playing == true) {
    makeMove();
}
}
function makeMove() {
if (who == 0) {
    aiStrat();
    game();
}
else {
    var confirmAction = confirm("Kas soovite visata täringuid?");
    if (confirmAction) {
    decision = 1;
    }
    else {
    decision = -1;
    }
    game();
}
}
function game() {
if (decision == 1) {
    setTimeout(rollDice(), 6000); // <--- THIS GETS EXECUTED INSTANTLY
    if (diceOne != 1 && diceTwo != 1){
        currentScore += diceOne + diceTwo;
//and so on

The code should look like this: 该代码应如下所示:

setTimeout(rollDice, 6000);

By adding the parentheses, you're calling the function and setting a timer for calling whatever that function returns. 通过添加括号,您可以调用该函数并设置计时器以调用该函数返回的内容。 You'll want to pass the function object itself. 您将要传递函数对象本身。

You can't immediately use diceOne and diceTwo after setting the timeout. 设置超时后,您不能立即使用diceOnediceTwo You have to put that code in the timeout function as well, for example: 您还必须将该代码放入超时函数中,例如:

setTimeout(function() {
    rollDice();

    if (diceOne != 1 && diceTwo != 1){
        currentScore += diceOne + diceTwo;
    ...
}, 6000);

That's because the code after setTimeout will not wait before the timeout has finished. 这是因为setTimeout之后的代码不会等待超时完成。

Try this: 尝试这个:

setTimeout(function(){
    rollDice()
}, 6000) 

调用rollDice函数时不需要括号。

    setTimeout(rollDice, 6000);

I would use something like this: 我会用这样的东西:

setTimeout(function(){rollDice()}, 6000); setTimeout(function(){rollDice()},6000);

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM