了解JavaScript setTimeout和setInterval [英] Understanding JavaScript setTimeout and setInterval

查看:129
本文介绍了了解JavaScript setTimeout和setInterval的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我需要一点帮助,了解和学习如何控制这些功能,以便我想要他们做的事情。

I need a bit of help understanding and learning how to control these functions to do what I intend for them to do

所以基本上我来自一个Java背景,并用乒乓球项目潜入JavaScript。我设法得到游戏运行与setInteval每20ms调用我的主游戏循环,所以这一切都可以。然而,我试图实现一个基本上使一个隐藏的div在轮之间可见的倒数到开始类型,设置它的 innerHTML =3// then2then 1然后GO!

So basically I'm coming from a Java background and diving into JavaScript with a "Pong game" project. I have managed to get the game running with setInteval calling my main game loop every 20ms, so that's all ok. However I'm trying to implement a "countdown-to-begin-round" type of feature that basically makes a hidden div visible between rounds, sets it's innerHTML = "3" // then "2" then "1" then "GO!".

我最初尝试通过将 setTimeout 在4循环for循环(3,2,1,go),但总是只显示最后一次迭代。我尝试修补了一点,但我不断回到这样的感觉,我错过了一个关于控制流程的基本概念。

I initially attempted to do this by putting setTimeout in a 4-iteration for-loop (3,2,1,go) but always only displayed the last iteration. I tried tinkering for a bit but I keep coming back to the feeling that I'm missing a fundamental concept about how the control flows.

我将发布相关代码从我的程序,我的问题基本上是如何写我的代码错误,我需要知道关于setTimeout和setInterval能够修复它,以执行我打算的方式。我有兴趣学习如何理解和掌握这些电话,所以虽然代码示例可以很好的帮助我理解,显然不是不受欢迎的,但我只是想说明,我不是在寻找你只是修复我的代码。另外,请不要jQuery。

I'll post the relevant code from my program, and my question would be basically how is it that I'm writing my code wrong, and what do I need to know about setTimeout and setInterval to be able to fix it up to execute the way I intend it to. I'm interested in learning how to understand and master these calls, so although code examples would be awesome to help me understand and are obviously not unwelcome, but I just want to make it clear that I'm NOT looking for you to just "fix my code". Also, please no jQuery.

整个程序将是一个很大的代码,所以我会尽量保持它的修剪和相关性:

The whole program would be a big wall of code, so I'll try to keep it trimmed and relevant:

//this function is called from the html via onclick="initGame();"
function initGame(){

    usrScore = 0;
    compScore = 0;
    isInPlay = true;

    //in code not shown here, these objects all have tracking variables
    //(xPos, yPos, upperBound, etc) to update the CSS
    board = new Board("board");
    ball = new Ball("ball");
    lPaddle = new LPaddle("lPaddle");
    rPaddle = new RPaddle("rPaddle");

    renderRate = setInterval(function(){play();}, 20);

}

function initNewRound(){

    /*
     * a bunch of code to reset the pieces and their tracking variables(xPos, etc)    
     */

    //make my hidden div pop into visibility to display countdown (in center of board)
    count = document.getElementById("countdown");
    count.style.visibility = "visible"; 


     //*****!!!! Here's my issue !!!!*****//

    //somehow i ends up as -1 and that's what is displayed on screen
    //nothing else gets displayed except -1
    for(var i = 3; i >= 0; i--){
        setInterval(function(){transition(i);}, 1000);
    }
}

//takes initNewRound() for-loop var i and is intended to display 3, 2, 1, GO!
function transition(i){
    count.innerHTML = (i === 0) ? "Go" : i;
}

//and lastly my main game loop "play()" just for context
function play(){

    if(usrScore < 5 && compScore < 5){

        isInPlay = true;
        checkCollision();
        moveBall();
        moveRPaddle();

        if(goalScored()){
            isInPlay = false;
            initNewRound();
        }
    }

} 

谢谢为了你的建议,我很新的JavaScript,所以我真的很感激。

Thanks a bunch for your advise, I'm pretty new to JavaScript so I really appreciate it.

推荐答案

展开Cookie怪兽的评论,当您在循环中使用setInterval时,您将排队执行方法,基础代码流已经完成。而不是排队多个setInterval执行,您可以对单个执行进行排队,并使用变量闭包或全局计数器跟踪当前计数。在下面的例子中,我使用了一个全局变量:

Expanding on cookie monster's comment, when you use setInterval in a loop, you are queueing up method executions that will run after the base code flow has completed. Rather than queue up multiple setInterval executions, you can queue up a single execution and use a variable closure or global counter to track the current count. In the example below, I used a global variable:

var i = 3 // global counter;
var counterInterval = null; // this will be the id of the interval so we can stop it

function initNewRound() {
    // do reset stuff

    counterInterval = setInterval(function () { transition() }, 1000); // set interval returns a ID number
}

// we don't need to worry about passing i, because it is global
function transition() {
    if (i > 0) {
        count.innerHTML = i;
    }
    else if (i === 0) {
        count.innerHTML = "Go!";
    }
    else {
        i = 4; // set it to 4, so we can do i-- as one line
        clearInterval(counterInterval); // this stops execution of the interval; we have to specify the id, so you don't kill the main game loop
    }

    i--;
}

这是一个小提琴演示

这篇关于了解JavaScript setTimeout和setInterval的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆