var myInterval;
var interval_delay = 500;
var is_interval_running = false; //Optional
$(document).ready(function () {
$(window).focus(function () {
clearInterval(myInterval); // Clearing interval if for some reason it has not been cleared yet
if (!is_interval_running) //Optional
myInterval = setInterval(interval_function, interval_delay);
}).blur(function () {
clearInterval(myInterval); // Clearing interval on window blur
is_interval_running = false; //Optional
});
});
interval_function = function () {
is_interval_running = true; //Optional
// Code running while window is in focus
}