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?
.ready()
(or.load()
) tooclearInterval()
is called only on stuff2. Use different interval_id for both of them.Created a snippet for you: