I am trying to make it so a div refreshes with ajax. The code itself is implemented and working already. I want the div to refresh every 30 seconds but only on an active tab. From what I understand setInterval will refresh every time regardless of whether the tab is in use or not. Id like to combine a mouseenter (or some other kind of user interaction that implies the user is active on the site) with setInterval so that the setInterval doesnt get fired if inactive.
currently I have this code which works well on the initial page load. There is no refresh during the first 30 seconds, nor is there a refresh until mouseenter on the div. However after the initial 30 seconds it refreshes on every 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.
});
Just set the interval when the mouse cursor is in the tab you want, and clear it when it’s outside:
Now the
<div>is refreshed in the instant the mouse enters inside its borders, and every 30 seconds from that moment. This stops when the mouse leaves the<div>.If the mouse enters again, it checks for the last time the
refreshfunction was called. If less than 30 seconds have passed, it waits until 30 seconds pass.Pro-tip:
clearIntervalalso clears timed events generated bysetTimeout, just likeclearTimeoutcancelssetInterval.