Запустите и остановите обновление AJAX в зависимости от видимости. Вы можете использовать .is()
, чтобы вернуть ИСТИНА или ЛОЖЬ для :visible
:
var timer; // Variable to start and top updating timer
// This if statement has to be part of the event handler for the visibility
// change of selector..... so there might be more straight forward solution
// see the last example in this answer.
if ($(selector).is(":visible"))
{
// Start / continue AJAX updating
timer = setInterval(AJAXupdate, 1000);
} else
{
// Stop AJAX updating
clearInterval(timer);
}
Вот простой пример таймера, который останавливается, когда он невидим. Обратите внимание, что цифры не продолжают увеличиваться, когда они не видны:
(function() {
var switcher; // variable to start and stop timer
// Function / event that will be started and stopped
function count() {
$("div").html(1 + parseInt($("div").html(), 10));
}
$(function() { // <== doc ready
// Start timer - it is visible by default
switcher = setInterval(count, 1000);
$("input").click(function() {
$("div").toggle(); // Toggle timer visibility
// Start and stop timer based on visibility
if ($("div").is(":visible"))
{
switcher = setInterval(count, 1000);
} else
{
clearInterval(switcher);
}
});
});
}());
Конечно, в приведенном выше случае, и, возможно, в вашем случае, проще просто поочередно включать и выключать обновление:
(function() {
var switcher;
function count() {
$("div").html(1 + parseInt($("div").html(), 10));
}
$(function() {
switcher = setInterval(count, 1000);
$("input").toggle(function() {
clearInterval(switcher);
$("div").toggle(); },
function() {
switcher = setInterval(count, 1000);
$("div").toggle();
});
});
}());