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

标签 javascript jquery timeout

我有一个为页面的单个元素加载内容的函数和一个为所有元素重新加载内容的函数。为此,它为每个元素调用 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() 运行时的所有超时?

最佳答案

尝试更改此行:

clearTimeout(i);

至:

clearTimeout(timeouts[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);
}

关于JavaScript:将超时保存在数组中并将其全部清除,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/24489527/

相关文章:

javascript - 服务 worker 获取事件未触发

javascript - JQuery:on 无法正常工作

jquery - 用jquery-ajaxq实现重试逻辑的最佳方法是什么?

python aiohttp超时是针对单个TCP连接还是针对http请求?

javascript - 在 Meteor 中使用 fs 模块获取 Uncaught TypeError _fs2.default.readFile 不是函数

javascript - 使用 SVG.js 的蜜蜂 SVG 动画

javascript - 附加到父级,显示所有复选框值

javascript - jQuery UI - 当 droppable 必须删除拖动的元素时怎么办?

Jquery 模态窗口帮助

timeout - 如何避免travis_wait之后显示日志?