JavaScript:在数组中保存超时并清除它们

时间:2014-06-30 11:52:35

标签: javascript jquery timeout clear

我有一个为页面的单个元素加载内容的函数和一个为所有元素重新加载内容的函数。为此,它为每个元素调用singleContent函数。

这两个函数都有各自的计时器,应该在重新加载所有内容时重置。

// i want to save all setTimeout references here, so that I can easily reset them
var timeouts = [];

// reloads content for single element
function singleContent(selector)
{
    // get and replace content [...]

    // get time for setTimeout from content object [...]
    var time = someFunction();

    // call itself again after specified time and save timeout to timeouts[]
    timeouts.push(setTimeout(function() {singleContent(selector)}, time));
}

// reloads all content by calling singleContent for all elements
function allContent()
{
    // reset timeouts[]
    for (var i = 0; i < timeouts.length; i++) {
        clearTimeout(i);
    }
    timeouts = [];

    //load content
    $("#content").fadeOut(2000, function() {
            $("#content .box").each(function() {
                singleContent(this);
            });
            $("#content").fadeIn(2000);

            // call itself again after specified time
            setTimeout(function() {allContent()}, 30000);
    }); 

}

allContent()

它到目前为止工作,但不知何故,超时数组不断增长。它已清空,但所有超时似乎都在后台运行。当allContent()运行时,如何清除所有超时?

1 个答案:

答案 0 :(得分:1)

尝试更改此行:

  

clearTimeout(ⅰ);

为:

  

clearTimeout(超时[I]);

我认为allContent超时也是错误的地方

// reloads all content by calling singleContent for all elements
function allContent()
{
   // reset timeouts[]
   for (var i = 0; i < timeouts.length; i++) {
      clearTimeout(timeouts[i]);
    }
    timeouts = [];

    //load content
    $("#content").fadeOut(2000, function() {
            $("#content .box").each(function() {
                singleContent(this);
            });
            $("#content").fadeIn(2000);

            // call itself again after specified time
    });
    // Need here or the callbacks will be growth exponential (every each start a new timeout)
    setTimeout(function() {allContent()}, 30000);
}
相关问题