![](/img/trans.png)
[英]want to play audio and it should be stop after 10 seconds inHtml and javascript?
[英]stop execution after 10 seconds javascript / jquery
我正在使用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;
}
计数器停止,因为您仅运行代码以每10秒更新一次。
您正在使用具有10000毫秒延迟的setInterval
,因此,每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/
首先,您是如何使用setTimeout
函数的?
希望我能理解您要在此处实现最低目标的目标。
如果使用setInterval
来管理游戏循环,则可以设置具有10秒超时值的setTimeout
,以使用clearInterval
取消setInterval
游戏循环。 例如:
// 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.
);
我使用上述技术创建了一个小提琴 (到目前为止,它可以按预期工作)。 您可以将game_loop
interval值设置为game_loop
值, game_end_timeout
(调用clearInterval
)将确定游戏循环何时停止。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.