我正在尝试使 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.
});