2

我正在尝试使 div 使用 ajax 刷新。代码本身已经实现并且已经运行。我希望 div 每 30 秒刷新一次,但仅在活动选项卡上。据我了解,无论选项卡是否正在使用,setInterval 都会每次刷新。我想将 mouseenter(或暗示用户在网站上处于活动状态的某种其他类型的用户交互)与 setInterval 结合起来,这样 setInterval 在不活动时不会被触发。

目前我有这段代码在初始页面加载时效果很好。在前 30 秒内没有刷新,在 div 上的 mouseenter 之前也没有刷新。然而,在最初的 30 秒后,它会在每个 mouseenter 上刷新。

$(document).ready(function(){

    $("#container").hide();
    $("#loading").show();
    $("div#refresh").load('example.com/load.php', function(){ $("#container").show(); $("#loading").hide(); });

    function refresh() {
        $("#refresh").mouseenter(function() {
        //  $("#container").hide();
            $("#loading").show();
            $("div#refresh").load('example.com/load.php', function(){ $("#container").show(); $("#loading").hide(); });
        });
        clearInterval(intervalID);
    }

    var intervalID = setInterval(refresh, 30000); // Will alert every 30 second.
    // clearInterval(intervalID); // Will clear the timer.

});
4

3 回答 3

4

只需设置鼠标光标在您想要的选项卡中的时间间隔,并在它在外面时清除它:

var intervalID, lastRefresh = 0;
$("#refresh").mouseenter(function() {
    var diff = new Date().getTime() - lastRefresh;
    intervalID = setTimeout(function() {
        refresh();
        intervalID = setInterval(refresh, 30000);
    }, 30000 - diff);
}).mouseleave(function() {
    clearInterval(intervalID);
});

function refresh() {
    $("#loading").show();
    $("div#refresh").load('example.com/load.php',
            function(){ $("#container").show(); $("#loading").hide(); });
    lastRefresh = new Date().getTime();
}

现在在<div>鼠标进入其边界内的那一刻刷新一次,从那一刻起每 30 秒刷新一次。当鼠标离开时停止<div>

如果鼠标再次进入,它会检查最后一次refresh调用该函数的时间。如果不到 30 秒,它会等到 30 秒过去。

专业提示clearInterval还清除由 生成的定时事件setTimeout,就像clearTimeout取消一样setInterval

于 2012-08-26T15:50:19.607 回答
0

试试这个:

$(document).ready(function(){
    var intervalID;
    $("#container").hide();
    $("#loading").show();
    $("div#refresh").load('example.com/load.php', function(){ $("#container").show(); $("#loading").hide(); });

function refresh() {
        //  $("#container").hide();
            $("#loading").show();
            $("div#refresh").load('example.com/load.php', function(){ $("#container").show();     $("#loading").hide(); });
    }

 $("#refresh").mouseenter(function() {
     intervalID= setInterval(refresh, 30000); 
  });

$("#refresh").mouseleave(function() {
  clearInterval(intervalID);
 });
于 2012-08-26T15:53:06.033 回答
0
$(function(){
    var intervalID;
    $("#container").hide();
    refresh();

    function refresh() {
        $("#loading").show();
        $("div#refresh").load('example.com/load.php', function(){
            $("#container").show(); 
            $("#loading").hide(); 
        });
    }
    $("#refresh").on({
        mouseenter: function() {
            intervalID = setInterval(refresh, 30000);
        },
        mouseleave: function() {
            clearInterval(intervalID);    
        }
    });
});

​</p>

于 2012-08-26T15:56:14.180 回答