再次单击按钮时,clearTimeout无法正常工作

时间:2016-01-12 01:16:32

标签: javascript php jquery ajax cleartimeout

我有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>

1 个答案:

答案 0 :(得分:3)

您的功能showTime(gotoUrl,output,index)会在成功时调用showTimeX(gotoUrl, output)

showTimeX(gotoUrl,output,index)定义要求索引作为最后一个参数,在调用该函数时未指定。

可能是索引未定义,因此超时数组不包含任何变量吗?