10秒后停止执行javascript / jquery

时间:2013-07-29 11:01:27

标签: javascript jquery html css3

我正在开发一个简单的javascript游戏,只是为了学习jquery和动画,游戏很简单,只需要几个弹跳球就可以了。

$(document).ready(function() { 
        $('#stage').bind('click',function(e){ 
        $("#bomb").show(); 
        var x = e.clientX - this.offsetLeft -35 ;
        var y = e.clientY - this.offsetTop -35 ;
        $("#bomb").animate({left:x,top:y}, 200, function(){
        $("#bomb").hide(); 
        $("#bomb").css({ top: "365px",left:"240px"});
        $("#bomb").show(); 
                         });    
        }); 
                $("#box1").click(function() {hit("#box1");})
                $("#box2").click(function() {hit("#box2");})
                $("#box3").click(function() {hit("#box3");})


        });

我想在10秒后停止执行,但我没有说明如何实现这一点,我做了一个简单的setTimeout,当我点击(并激活绑定方法)时,计数器停止运行。 ..有什么建议吗?柜台的代码是:

var counter=setInterval(timer, 10000);
         function timer()
        { count=count-1;
        if (count < timeout)
    {   clearInterval(counter);
        imageUrl="img/BGgameover.gif"; 
        $('#stage').css('background-image', 'url(' + imageUrl + ')'); 
        $('#bomb').remove();  
        $('#stage').removeClass('running');
        return;
                        }
        document.getElementById("timer").innerHTML=count;
            }

2 个答案:

答案 0 :(得分:3)

您的计数器会停止,因为您只运行代码每10秒更新一次。

您正在使用setInterval延迟10000毫秒,因此每10秒调用timer函数,我认为您应该使用1秒间隔。

以下代码将每秒运行一次,因此“timer”div将使用剩余的秒数进行更新,然后当count变得小于timeout时,游戏代码将运行。

var counter = setInterval(timer, 1000);

// Make sure "count" and "timeout" are sane values. What are they defined to initially?

function timer() { 
  count = count - 1;

  if (count < timeout) {   
    clearInterval(counter);
    imageUrl = "img/BGgameover.gif"; 

    $('#stage').css('background-image', 'url(' + imageUrl + ')'); 
    $('#bomb').remove();
    $('#stage').removeClass('running');
    return;
  }

  document.getElementById("timer").innerHTML = count;
}

在旁注中,使用setInterval可能有点狡猾,您可能希望使用requestAnimationFrame代替:http://www.paulirish.com/2011/requestanimationframe-for-smart-animating/

答案 1 :(得分:1)

你是如何在第一时间使用setTimeout函数的?

让我们希望我明白你在这里想要达到的最低水平。

如果您使用setInterval来管理游戏循环,则可以设置具有10秒超时值的setTimeout,以使用setInterval取消设置clearInterval游戏循环。 E.g:

// Interval to do game functions at set timeframes.
var game_loop = window.setInterval(
    function_here,
    1000 // = 1 second, can be as long as short you need.
);

// Timeout to clear the above game interval loop.
var game_end_timeout = window.setTimeout(
    function() {
        window.clearInterval( game_loop );
        /* Possible additional cleanups here. */
    },
    10000 // = 10 seconds or whatever time you want to stop the loop execution.
);

I created a fiddle using the above technique(到目前为止按预期工作)。您可以将game_loop间隔值设置为您需要的值,game_end_timeout(调用clearInterval)将确定何时应停止游戏循环。

相关问题