I have countdown timer running on web and second function that periodically check changes in database, but it's more important to check it more often (let's say every 3 seconds) when timer is coming to an end and less often when timer starts. I have following code:
var days, hours, minutes, seconds, check_interval;
setInterval(function() {
var current_date = new Date().getTime();
var seconds_left = (date_end - current_date) / 1000;
days = parseInt(seconds_left / 86400);
seconds_left = seconds_left % 86400;
hours = parseInt(seconds_left / 3600);
seconds_left = seconds_left % 3600;
minutes = parseInt(seconds_left / 60);
seconds = parseInt(seconds_left % 60);
document.getElementById('countdown').innerHTML = days + 'd ' + hours + 'h ' + minutes + 'm ' + seconds + 's';
if (hours > 0) {
check_interval = 60000;
} else if (hours = 0 && minutes > 5) {
check_interval = 10000;
} else {
check_interval = 3000;
}
var check_bids = setInterval(function() {
$.ajax({
type: 'POST',
url: '/check.class.php',
dataType: 'json',
data: { ... }
}).done(function(response) {
...
}).fail(function(jqXHR, textStatus, errorThrown) {
console.log('Bids check failed: '+textStatus, errorThrown);
});
}, check_interval); // Accelerating interval
}, 1000);
It works as I want but I'm really not sure if I can combine these two setInteval functions like that? Is it effective at all? Thanks for advice.
UPDATE:
Thanks to Strille, I finally choose this simple solution with only one setInterval:
var days, hours, minutes, seconds;
setInterval(function() {
var current_date = new Date().getTime();
var seconds_left = seconds_to_end = (date_end - current_date) / 1000;
days = parseInt(seconds_left / 86400);
seconds_left = seconds_left % 86400;
hours = parseInt(seconds_left / 3600);
seconds_left = seconds_left % 3600;
minutes = parseInt(seconds_left / 60);
seconds = parseInt(seconds_left % 60);
document.getElementById('countdown').innerHTML = days + 'd ' + hours + 'h ' + minutes + 'm ' + seconds + 's';
if (hours > 0) { // If time to end is greater than 1 hour repeat ajax call every 60 seconds etc.
repeat_every_x_seconds = 60;
} else if (minutes > 5) {
repeat_every_x_seconds = 10;
} else {
repeat_every_x_seconds = 3;
}
if (parseInt(seconds_to_end) % repeat_every_x_seconds == 0) {
check(); // Call this function every x seconds.
}
}, 1000);
var check = function() {
$.ajax({
type: 'POST',
url: '/check.class.php',
dataType: 'json',
data: { ... }
}).done(function(response) {
...
}).fail(function(jqXHR, textStatus, errorThrown) {
...
});
};
Maybe it helps somebody. And sorry for english :)