I want to stop timer when browser tab is inactive or minimize but the issue is when I change browser tab or minimize and after maximize browser tab, count of timer display two time in the window body. Kindly suggest the solution
var window_focus;
$(window).focus(function() {
window_focus = true;
startCount();
});
$(window).blur(function() {
window_focus = false;
stopCount();
});
var c = 0;
var t;
var timer_is_on = 0;
function timedCount()
{
c = c+1;
t = setTimeout(function(){timedCount()},1000);
}
function startCount()
{
if (!timer_is_on)
{
timer_is_on=1;
timedCount();
}
}
function stopCount()
{
clearTimeout(t);
timer_is_on=0;
$('body').append('count' + c + '<br>');
}
I want to stop timer when browser tab is inactive or minimize but the issue is when I change browser tab or minimize and after maximize browser tab, count of timer display two time in the window body. Kindly suggest the solution
var window_focus;
$(window).focus(function() {
window_focus = true;
startCount();
});
$(window).blur(function() {
window_focus = false;
stopCount();
});
var c = 0;
var t;
var timer_is_on = 0;
function timedCount()
{
c = c+1;
t = setTimeout(function(){timedCount()},1000);
}
function startCount()
{
if (!timer_is_on)
{
timer_is_on=1;
timedCount();
}
}
function stopCount()
{
clearTimeout(t);
timer_is_on=0;
$('body').append('count' + c + '<br>');
}
Share
Improve this question
edited May 23, 2014 at 8:57
BenMorel
36.8k52 gold badges206 silver badges337 bronze badges
asked Dec 27, 2013 at 8:05
okconfusedokconfused
3,6374 gold badges26 silver badges38 bronze badges
5
- 1 Your best bet will be HMTL5's Page Visibility API. It is still expirimental. – A1rPun Commented Dec 27, 2013 at 8:08
- are you using same script.. the newly opened tab. – UdayKiran Pulipati Commented Dec 27, 2013 at 8:08
- can you create a fiddle for this ? – Sunil Verma Commented Dec 27, 2013 at 8:10
- yes udaykiran pulipati i m using same code see in jsfiddle jsfiddle/JWxS6/59 – okconfused Commented Dec 27, 2013 at 8:14
- jsfiddle link jsfiddle/JWxS6/59 – okconfused Commented Dec 27, 2013 at 8:15
1 Answer
Reset to default 6The only reliable way to do so is to use Visibility API offered by HTML5, it offers various ways to check browser visibility status.
for ex:
document.hidden // Returns true if the page is hidden
and
document.visibilityState // Returns a string telling state of visibility
also you can add listener on change of browser visibility states as follows :
document.addEventListener("visibilitychange", function() {
console.log(document.hidden, document.visibilityState);
}, false);
but this does not work in all browsers, so you need to test this in multiple browsers before starting on this.