javascript - 如何使用 Jquery/javascript 将递归函数转换为循环函数

标签 javascript jquery recursion iteration slideshow

我正在尝试使用 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();

);

到目前为止,我的两种方法是:

  1. 在 $(document).ready() 函数和循环 playslides() 函数中创建一个 while 循环。

  2. 创建另一个调用 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/

相关文章:

javascript - 如何通过 jQuery 保持鼠标悬停的 DIV 可见?

javascript - 将 View 的触摸位置转换为 WebView 的 HTML 屏幕位置

javascript - 如何触发 Angular 从 JQuery 重新编译模板?

javascript - 我的 antlr 4 左递归表达式不保留表达式优先顺序

c++ - 二叉树的递归析构函数?

javascript - ul li a affecting ul li ul li a

javascript - 在嵌套的 ng-repeat 中使用带有单选按钮的 ng-model 不起作用

c# - 完成后关闭的新弹出窗口?

jQuery UI Slider 和 handle-modification

SQL Server : CTE (recursion), 在 CTE 之外设置条件