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