jQuery execute multiple functions only on focus. 2 Problems

315 views Asked by At

I found many codes for executing multiple functions every second only when the window is on focus but they are either not working or not working right. For example this code:

<div id="test""></div>
<br>
<div id="test2"></div>
<script language="javascript" type="text/javascript">
var interval_id;
$(window).focus(function() {
    if (!interval_id)
        interval_id = setInterval(stuff1, 1000);
        interval_id = setInterval(stuff2, 1000);
});

$(window).blur(function() {
    clearInterval(interval_id);
    interval_id = 0;
});



function stuff1(){
    $("#test").append("1" + " ");
}
function stuff2(){
    $("#test2").append("2" + " ");
}
</script>

So I want stuff1 and stuff2 to be executed every second. Problem 1: It don't start when I call the page first time, I need to open another page/hide this page and return to it so the functions start.

Problem 2: When I return to this page second time stuff1 is getting executed twice as fast, so every 0.5 seconds, on third time 0.33 seconds and so on. What is wrong here and how can I do it right?

1

There are 1 answers

1
Salil Dabholkar On BEST ANSWER
  1. Maybe you need to call the function on .ready() (or .load()) too
  2. clearInterval() is called only on stuff2. Use different interval_id for both of them.

Created a snippet for you:

var interval_id;
$(window).focus(function() {
  if (!interval_id) {
    interval_id1 = setInterval(stuff1, 1000);
    interval_id2 = setInterval(stuff2, 1000);
  }
});

$(window).blur(function() {
  clearInterval(interval_id1);
  clearInterval(interval_id2)
  interval_id1 = interval_id2 = 0;
});

function stuff1() {
  $("#test").append("1" + " ");
}

function stuff2() {
  $("#test2").append("2" + " ");
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div id="test" style="margin-top: 40px;"></div>
<br>
<div id="test2" style="margin-top: 40px;"></div>