我有两个Ajax函数,每个函数读取一组数字。这只是一个演示,所以假设语法正确并且所有数据加载正确。每个函数都有一个setTimeout,它每2秒重新加载一次数据。
我正试图在我能做的两个功能之间切换,但当我切换时,我似乎无法阻止超时触发。两个超时同时触发。
这是HTML文件-
<button class="btn low-btn">Get Low Numbers</button>
<button class="btn high-btn">Get High Numbers</button>
<div class="numbers"></div>
<script src="data.js"></script>
这是data.js文件-
$(document).ready(function(){
var timeout_high;
var timeout_low;
function low() {
$.ajax('get-low.php', {
success: function (data) {
$(".numbers").replaceWith("<div class='numbers'>Low Numbers: "+data+"</div>");
var timeout_low = setTimeout(low, 2000);
}
});
}
function high() {
$.ajax('get-high.php', {
success: function (data) {
$(".numbers").replaceWith("<div class='numbers'>High Numbers: "+data+"</div>");
var timeout_high = setTimeout(high, 2000);
}
});
}
$(".low-btn").click(function(){
clearTimeout(timeout_high);
low();
});
$(".high-btn").click(function(){
clearTimeout(timeout_low);
high();
});
});
我试着在点击按钮后使用clearTimeout,但它并没有终止超时,但两个功能都在继续启动。如果我一直点击,它只会增加更多的超时。
下面的两行:
var timeout_low = setTimeout(low, 2000);
var timeout_high = setTimeout(high, 2000);
不是为$(document).ready
函数开头定义的变量分配新值,而是为相应函数创建新值。所以clearTimeouts实际上什么都不做——它们在ajax:成功处理程序之外运行,只看到"外部"变量。
(是的,clearTimeout(undefined)
既不抛出也不警告(
最简单的解决方案是从这些语句中删除var
:
timeout_low = setTimeout(low, 2000);
timeout_high = setTimeout(high, 2000);
尽管如此,我还是强烈考虑将这些函数合并为一个函数,使用某种字典,将数据获取器和它们的结果应该显示在其中的元素联系在一起