If you want the code to run every 5 seconds and an ad hoc call to the code should reset the 5 second interval, then you need to capture the return of setTimeout
and clear it with clearTimeout
[MDN] within getOpenTickets
:
$(document).ready(function(){
var openTicketRequests = [];
var timeoutID = null;
function getOpenTickets() {
// First clear the timer.
clearTimeout(timeoutID);
// Abort all pending openTicketRequests
for(var i=0; i<openTicketRequests.length; i++) {
openTicketRequests[i].abort();
}
openTicketRequests.push(
$.ajax({
type: "GET",
url: "ticket/get_open",
dataType: "json",
success: function(data) {
$(".open_tickets").empty(); // Empty the list of open tickets.
for (var i=0; i<data.length; i++) {
$(".open_tickets").append(data[i].id + "<br/>");
}
}
}));
timeoutID = setTimeout(getOpenTickets, 5000);
}
});
If you want the code to run every 5 seconds regardless of whether you've executed the code in an ad hoc fashion, I would separate the code that creates the regular call from the call itself and use setInterval
[MDN] instead of setTimeout
:
$(document).ready(function(){
var openTicketRequests = [];
function getOpenTickets() {
// Abort all pending openTicketRequests
for(var i=0; i<openTicketRequests.length; i++) {
openTicketRequests[i].abort();
}
openTicketRequests.push(
$.ajax({
type: "GET",
url: "ticket/get_open",
dataType: "json",
success: function(data) {
$(".open_tickets").empty(); // Empty the list of open tickets.
for (var i=0; i<data.length; i++) {
$(".open_tickets").append(data[i].id + "<br/>");
}
}
}));
}
setInterval(getOpenTickets, 5000);
});
Now, you can call getOpenTickets
ad hoc whenever you want, but it's not going to compound the regular call.