简体   繁体   English

JavaScript:将超时保存在数组中并全部清除

[英]JavaScript: save timeouts in array and clear them all

I have a function that loads content for single elements of a page and a function that reloads content for all elements.我有一个为页面的单个元素加载内容的函数和一个为所有元素重新加载内容的函数。 To do that, it calls the singleContent function for each element.为此,它为每个元素调用 singleContent 函数。

Both functions have individual timers that should be reset when all content is reloaded.这两个函数都有单独的计时器,当所有内容重新加载时,这些计时器应该被重置。

// 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()

It works so far, but somehow the timeouts array keeps growing bigger.到目前为止它有效,但不知何故超时数组不断变大。 It is emptied, but all the timeouts seem to keep running in the background.它被清空了,但所有超时似乎都在后台运行。 How do I clear all the timeouts when allContent() is running?当 allContent() 运行时如何清除所有超时?

try to change this line:尝试更改此行:

clearTimeout(i);清除超时(i);

to:到:

clearTimeout(timeouts[i]);清除超时(超时[i]);

I think the allContent timeout is at a wrong place too我认为 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);
}

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM