Reputation: 2714
I am using datatable and there is an option to use setInterval
in order to refresh the table content.
The problem is, that the network traffic is increasing when the user stays on that page and if the page is doing a consistent reload every second of the same dataset.
I want to stop after 10 seconds, because I think this is the average time a user stays on that page before going somewhere else.
Not sure how to include the 10 second timeout, below is my code so far:
setInterval(function() {
$('#Table1').DataTable().ajax.reload(null, false);
}, 1000);
Upvotes: 0
Views: 1399
Reputation: 271
var interval = setInterval(function() {
$('#Table1').DataTable().ajax.reload(null, false);
}, 1000);
setTimeout(function() { clearInterval(interval); }, 10000);
Example code snippet:
var interval = setInterval(function() {
console.log("Interval fired");
}, 1000);
setTimeout(function() { clearInterval(interval); }, 10000);
Upvotes: 1
Reputation: 33
var myInterval = setInterval(function() {
$('#Table1').DataTable().ajax.reload(null, false);
}, 1000);
setTimeout(function() {
clearInterval(myInterval);
}, 10000);
I suggest that you use a setTimeout function in the response callback of your Ajax call and have a count variable that counts to 10 each time setTimeout is executed, and clearInterval when count reaches 10. This would be more efficient if your request takes a longer time to process.
Upvotes: 1
Reputation: 1201
Simply cancel the setInterval
after 10 seconds pass (using setTimeout
). You can clear an interval timer using clearInterval
.
var refreshInterval = setInterval(function() {
$('#Table1').DataTable().ajax.reload(null, false);
}, 1000);
setTimeout(function() {
clearInterval(refreshInterval);
}, 1000 * 10);
The asynchronous nature of JavaScript enables both setInterval
and setTimeout
to run at the appropriate times and without one blocking the other.
Upvotes: 1
Reputation: 3631
First var foo = setInterval(...
and then stop it after 3 seconds setTimeout(function(){ clearInterval(foo); }, 3000);
Upvotes: 0