我正在尝试使用 Jquery 制作幻灯片,图片由每 5.5 秒调用一次的函数循环播放。但是,我试图避免递归,因为与迭代调用相比它非常昂贵。我假设这就是 IE 在加载我的幻灯片时具有不间断加载图标的原因。所以我想将以下函数转换为迭代函数。
function playslides()
{
//hide previous slide
$(document.getElementById(t)).fadeOut("slow");
//reset slide index
calcSildes();
//show new slide
$(document.getElementById(t)).fadeIn("slow");
//recursive call after 5.5 sec
timer = setTimeout("playslides()", 5500);
}
//on page load...
$(document).ready(
playslides();
);
到目前为止,我的两种方法是:
在 $(document).ready() 函数和循环 playslides() 函数中创建一个 while 循环。
创建另一个调用 playslides() 函数的计时器函数,并让 playslides 函数调用该计时器函数。 (不确定这是否完全避免了递归...)
谢谢!!
最佳答案
听起来你应该用 setInterval()
替换 setTimeout()
,这将简单地重复给定的函数,直到它被取消。无需递归或循环。
Quoting John Resig , jQuery 的创造者:
At a fundamental level it's important to understand how JavaScript timers work. Often times they behave unintuitively because of the single thread which they are in. Let's start by examining the three functions to which we have access that can construct and manipulate timers.
var id = setTimeout(fn, delay);
- Initiates a single timer which will call the specified function after the delay. The function returns a unique ID with which the timer can be canceled at a later time.
var id = setInterval(fn, delay);
- Similar to setTimeout but continually calls the function (with a delay every time) until it is canceled.
clearInterval(id);
,clearTimeout(id);
- Accepts a timer ID (returned by either of the aforementioned functions) and stops the timer callback from occurring.
使用 setInterval
,您可以将代码简化为以下内容:
function playslides()
{
//hide previous slide
$(document.getElementById(t)).fadeOut("slow");
//reset slide index
calcSildes();
//show new slide
$(document.getElementById(t)).fadeIn("slow");
}
$(document).ready(function() {
setInterval(playslides, 5500);
});
关于javascript - 如何使用 Jquery/javascript 将递归函数转换为循环函数,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/8747931/