Page 1 of 1

JS timer help

Posted: Tue Mar 11, 2014 1:49 pm
by nite4000
Let me start off by saying that I am trying to help a friend out and I don't know a lot of JS but I know some but I am stumped on how to make this work right.

I need to make it so if the user is watching the timer and view the site related to the timer and he should open a new tab to browse a different site the timer stops until they go back to the correct tab.

Here is the code I have

Code: Select all

<script type="text/javascript">
var isActive;
window.onfocus = function () { 
  isActive = true; 
document.getElementById("clock").style.display="display";
document.getElementById("alert").innerHTML="";
}; 

window.onblur = function () { 
  isActive = true; 
//document.getElementById("alert").innerHTML="Timer Paused ! Click here to Activate it Again.";
}; 
function startClock() {

if(isActive == true)
{
	var the_timer = window.document.the_form.clock.value;
	the_timer = parseInt(the_timer) - 1;
	window.document.the_form.clock.value = the_timer;
}

the_timeout = setTimeout("startClock();",1000);

	if (the_timer == 0) {
document.getElementById("clock").style.display="none";
window.onblur = function () { 
document.getElementById("alert").innerHTML="";
};
	var answer = "";
		x = answer;
		document.the_form.clock.value = x;
clearTimeout(the_timeout);

               var code = "<?php
if($loggedin==1)
{
$site_code = md5(time().sha1(microtime()));
} else {
$site_code = "undefined";
}
$_SESSION["adcode"] = $site_code;
echo $_SESSION['adcode'];

?>";

               var ad= "<?php echo $_GET['ad']; ?>";
	success.location.href="success.php?ad="+ad+"&code="+code+"&verify=1";


	}
}

</script>


Any help would be great to get this fixed I am sure its a easy solution to it.

Re: JS timer help

Posted: Tue Mar 11, 2014 2:33 pm
by Christopher
You might want to try requestAnimationFrame() which only runs when the window is visible.

Re: JS timer help

Posted: Tue Mar 11, 2014 2:37 pm
by nite4000
any idea how I would add that into the code.. or somewhere I can get example code from?

Re: JS timer help

Posted: Tue Mar 11, 2014 4:53 pm
by Christopher
Honestly, I think you could just about replace setTimeout() with requestAnimationFrame(), but search for "requestAnimationFrame" and you will get plenty of examples, tutorials, etc.