I have 2 button, and when either buttons is clicked, the time is shown below. Both buttons have separate outputs. I'm trying to use clearTimeout, but it's not clearing the timeout for some reason. When a button is clicked again, it just makes another ajax call on top of the already existing ajax call. How do I get clearTimeout to work?
<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>
Your function showTime(gotoUrl,output,index)
calls showTimeX(gotoUrl, output)
on success.
But the showTimeX(gotoUrl,output,index)
definition requires index as last argument, which is not specifed when you call that function.
Could it be that index is undefined and so timeout array doesn't contain any variables?