Стартирайте и спрете актуализацията на AJAX въз основа на видимостта. Можете да използвате .is()
, за да върнете TRUE или FALSE за < a href="http://api.jquery.com/visible-selector/" rel="nofollow">: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();
});
});
}());
person
Peter Ajtai
schedule
05.10.2010