【发布时间】:2025-12-15 19:00:02
【问题描述】:
我想在 JavaScript 中使用递归来产生无限循环。事实上,我希望给图像一个来来去去的效果,没完没了。
让我们先看一些代码:
function lightening(){
$('#pic_holder').fadeOut(250).fadeIn(250);
setTimeout('lightening', 250);
}
这个函数,正如它所写的,应该
- 应用
fadeOut(250)和fadeIn(250)效果; - 使用
setTimeout函数,该函数必须递归调用lightening函数,此后重新应用 [fadeOut-fadeIn 效果 和 setTimeout] 块代码。
您会同意,这应该无限期地进行,但事实并非如此。
这是full test code, with HTML,您可以注意到,它只应用了一次fadeOut-fadeIn 效果。
我做错了什么?
【问题讨论】:
-
请注意,对“fadeOut”和“fadeIn”的调用将立即返回,即使效果需要 500 毫秒。如果您在 250 毫秒内开始下一个周期,您将积压工作。
-
另请注意,您问题中的代码不是递归的。异步和递归是完全不同的东西。
-
@FrédéricHamidi 我会说两者兼而有之。
-
@basilikum - 怎么样?根据wikipedia:
Recursion in computer programming is exemplified when a function is defined in terms of simpler, often smaller versions of itself. The solution to the problem is then devised by combining the solutions obtained from the simpler versions of the problem. -
@basilikum - 也来自*:
The main disadvantage is often that the algorithm may require large amounts of memory if the depth of the recursion is very large.。这似乎暗示了一个堆栈(我在这里忽略了 TCO),每个调用都返回状态。这只是在模仿setInterval,我希望我们能同意它是不是递归。
标签: javascript jquery