在JavaScript中,如何在一段时间后停止递归函数?
我在做这些随机的东西。 就像一个随机的潜水艇在附近盘旋。 现在,当鼠标悬停时,函数将启动,但如何在一段时间后自动停止名为animateDiv()的函数。 谢谢 这是代码 html代码在JavaScript中,如何在一段时间后停止递归函数?,javascript,jquery,Javascript,Jquery,我在做这些随机的东西。 就像一个随机的潜水艇在附近盘旋。 现在,当鼠标悬停时,函数将启动,但如何在一段时间后自动停止名为animateDiv()的函数。 谢谢 这是代码 html代码 <div class="a"> <button id="myButton">Click Me ;)</button> </div> 您可以通过设置超时来停止它 setTimeout(function (){ $('.a').stop(); }, "1
<div class="a">
<button id="myButton">Click Me ;)</button>
</div>
您可以通过设置超时来停止它
setTimeout(function (){
$('.a').stop();
}, "1000");
这将在1秒后停止类为
a
的任何元素上的任何动画。您必须使用某种变量来检查是否要设置动画
var do_animation = true;
function animateDiv() {
var newq = makeNewPosition();
$('.a').animate({
top: newq[0],
left: newq[1],
}, 400, function () {
if(do_animation) // The condition, if false this will not execute.
animateDiv();
});
};
然后,当您想停止它时,只需将
do_animation
设置为false
您不需要停止它,而是在一段时间后不运行它。只需输入一个条件来决定是否需要运行它
$('.a').animate(
{ top: newq[0], left: newq[1], },400, function ()
{
// put a condition here
if(Math.random() > .01){ // will stop after a while
animateDiv();
}
});
在这里,这将在两秒钟后停止动画功能。我已经用注释“//newchange”标记了我所做的更改。可以使用setTimeOut函数控制动画运行的时间(以毫秒为单位)。例如,我用了2秒钟。您还可以使用随机生成器设置此值,以获得不同的时间跨度
var animate = false; //new change
$(function () {
$('.a').mouseenter(function() {
animate = true;//new change
animateDiv();
setTimeout(function(){animate = false },2000)//new change
});
});
function makeNewPosition() {
var h = $(window).height() - 50;
var w = $(window).width() - 50;
var nh = Math.floor(Math.random() * h);
var nw = Math.floor(Math.random() * w);
return [nh, nw];
}
function animateDiv() {
var newq = makeNewPosition();
console.log(newq);
$('.a').animate(
{top: newq[0],
left: newq[1], }
,400, function () {
if(animate) animateDiv();//new change
});
};
这是一本书。检查控制台日志
这就是它的工作原理。在递归函数中开始动画之前,请将动画标志设置为true。仅当此标志为true时,函数才会调用自身。然后启动一个saperate计时器,使animate标志为false,这将导致递归函数中断
PS:你原始问题中的动画代码无论如何都不起作用。但是我没有试着调试它,因为您的问题只是关于如何在一段时间后停止函数 你想什么时候更改?设置一个全局标志,并在你可以传递给animate的step函数中检查它。在setTimeout()块中写入你的代码(animateDiv())。我想在几秒钟后鼠标悬停在按钮上时更改它。这看起来是一个糟糕的实现。animate()的匿名回调函数需要保存其上下文,因此它将保留在内存中。使用
setTimeout
和clearTimeout
更好。谢谢你的好友
var animate = false; //new change
$(function () {
$('.a').mouseenter(function() {
animate = true;//new change
animateDiv();
setTimeout(function(){animate = false },2000)//new change
});
});
function makeNewPosition() {
var h = $(window).height() - 50;
var w = $(window).width() - 50;
var nh = Math.floor(Math.random() * h);
var nw = Math.floor(Math.random() * w);
return [nh, nw];
}
function animateDiv() {
var newq = makeNewPosition();
console.log(newq);
$('.a').animate(
{top: newq[0],
left: newq[1], }
,400, function () {
if(animate) animateDiv();//new change
});
};