我有 2 个按钮,当单击任一按钮时,时间如下所示。两个按钮都有单独的输出。我正在尝试使用 clearTimeout,但由于某种原因它没有清除超时。当再次单击按钮时,它只会在已经存在的 ajax 调用之上进行另一个 ajax 调用。如何让 clearTimeout 工作?
<input type = 'submit' value = 'show time' onclick = "showTime('test1.php', 'output1',0)">
<div id = 'output1'></div>
<input type = 'submit' value = 'show time' onclick = "showTime('test1.php', 'output2',1)">
<div id = 'output2'></div>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.3/jquery.min.js"></script>
<script type = "text/javascript">
var timeout = [];
function showTime(gotoUrl,output,index) {
if (timeout[index]) {
clearTimeout(timeout[index]);
}
$.ajax({
type: "POST",
url: gotoUrl,
error: function(xhr,status,error){alert(error);},
success:function(data) {
document.getElementById( output ).innerHTML = data;
showTimeX(gotoUrl, output);
} //end of success:function(data)
}); //end of $.ajax
} //end of function showTime(gotoUrl, output)
function showTimeX(gotoUrl,output,index) {
$.ajax({
type: "POST",
url: gotoUrl,
error: function(xhr,status,error){alert(error);},
success:function(data) {
document.getElementById( output ).innerHTML = data;
timeout[index] = setTimeout(function(){showTimeX(gotoUrl, output, index)}, 5000);
} //end of success:function(data)
}); //end of $.ajax
} //end of function showTime(gotoUrl, output)
</script>