[英]How do I use cleartimeout to stop a recursive settimeout function in .getJSON?
[英]How to stop a function running after a number of seconds? setTimeout, clearTimeout and setInterval wont work correctly
所以我想做的是在游戏中几秒钟后停止某个功能。 我有一项基本功能,可以提高游戏的得分。
function increaseScore() {
score = score + 1; // increase score
display_score.innerHTML = "score is " + score; // prints new score
}
我在整个游戏中多次使用此代码,例如两个圈子。 红色圆圈……
if(red_circle == 0) {//stop the incrementing the clicker
increaseScore();
red_circle = 1;}
和绿色圆圈.....
if(green_circle == 0) {//stop the incrementing the clicker
increaseScore();
green_circle = 1;}
我想做的是在两个圆圈上经过一定的秒数后,停止这种增加分数的递增功能。 我尝试了setTimeout在4秒后得分之后以增量递增
if(red_circle == 0) {//stop the incrementing the clicker
setTimeout(function() { increaseScore();
red_circle = 1;
}, 4000);
}
和clearTimeout根本不允许分数增加
if(green_circle == 0) {//stop the incrementing the clicker
clearTimeout(function() { increaseScore();
green_circle = 1;
}, 3000);
}
和setInterval()。我的思维过程是否错误? 提前致谢
如果函数在循环中运行,则可以在循环内部检查其运行时间,如果运行时间过长,则可以中断循环。 如果从外部在循环中调用该函数,则调用代码可以执行相同的检查。 调用者可以记住它开始调用该函数的时间,并与当前时间进行比较。
var timeStarted = new Date();
// in the loop:
var currentTime = new Date();
if ((currentTime - timeStarted) < 4 * 1000)
{
// call the function
}
看来您没有按需使用clearTimeout函数。
为了使用clearTimeout,您需要首先从setTimeout函数中获取返回对象。
这是代码示例:
var myVar;
function myFunction() {
myVar = setTimeout(function(){ alert("Hello"); }, 3000);
}
function myStopFunction() {
clearTimeout(myVar);
}
请在w3schools中看看如何使用这些功能或在MDN上
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.