【发布时间】: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