【问题标题】:JavaScript: save timeouts in array and clear them allJavaScript:将超时保存在数组中并全部清除
【发布时间】:2014-08-20 18:56:36
【问题描述】:

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

【问题讨论】:

    标签: javascript jquery timeout


    【解决方案1】:

    尝试改变这一行:

    clearTimeout(i);

    到:

    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);
    }
    

    【讨论】:

    • facepalm 谢谢,完全错过了! D:现在可以了。
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2012-02-10
    • 2012-12-29
    • 1970-01-01
    • 1970-01-01
    • 2013-10-09
    相关资源
    最近更新 更多