views:

720

answers:

4

I have a function that is called every second that I only want to run if the current page is in the foreground, i.e. the user hasn't minimized the browser or switched to another tab. It serves no purpose if the user isn't looking at it and is potentially CPU-intensive, so I don't want to just waste cycles in the background.

Does anyone know how to tell this in JavaScript?

Note: I use jQuery, so if your answer uses that, that's fine :).

+11  A: 

You would use the focus and blur events of the window:

var interval_id;
$(window).focus(function() {
    interval_id = setInterval(hard_work, 1000);
});

$(window).blur(function() {
    clearInterval(interval_id);
});
BipedalShark
does that works? tested? that simple?
thephpdeveloper
@thephpdeveloper: Sure. If you have firebug, try a simple `console.log('test')` call for either event.
BipedalShark
cool! will test out when free. +1
thephpdeveloper
Works great. I start an interval in focus and stop it on blur.
ckknight
A: 

If you are trying to do something similar to google search engine when open in Chrome where certain event are triggered when you 'focus' on the page, try if hover() event answers your requirement.

#(window).hover(function() {
  // code here...
});
rockacola
+1  A: 

I would try to set a flag on the window.onfocus and window.onblur events.

The following snippet has been tested on Firefox, Safari and Chrome, open the console and move between tabs back and forth:

var isActive;

window.onfocus = function () { 
  isActive = true; 
}; 

window.onblur = function () { 
  isActive = false; 
}; 

// test
setInterval(function () { 
  console.log(window.isActive ? 'active' : 'inactive'); 
}, 1000);

Try it out here.

CMS
example is awesome. any idea about IE?
thephpdeveloper
+1  A: 

Using jQuery:

$(function() {
    window.isActive = true;
    $(window).focus(function() { this.isActive = true; });
    $(window).blur(function() { this.isActive = false; });
    showIsActive();
});

function showIsActive()
{
    console.log(window.isActive)
    window.setTimeout("showIsActive()", 2000);
}

function doWork()
{
    if (window.isActive) { /* do CPU-intensive stuff */}
}
cxfx