JS timer help

JavaScript and client side scripting.

Moderator: General Moderators

Post Reply
nite4000
Forum Contributor
Posts: 209
Joined: Sun Apr 12, 2009 11:31 am

JS timer help

Post 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.
User avatar
Christopher
Site Administrator
Posts: 13596
Joined: Wed Aug 25, 2004 7:54 pm
Location: New York, NY, US

Re: JS timer help

Post by Christopher »

You might want to try requestAnimationFrame() which only runs when the window is visible.
(#10850)
nite4000
Forum Contributor
Posts: 209
Joined: Sun Apr 12, 2009 11:31 am

Re: JS timer help

Post by nite4000 »

any idea how I would add that into the code.. or somewhere I can get example code from?
User avatar
Christopher
Site Administrator
Posts: 13596
Joined: Wed Aug 25, 2004 7:54 pm
Location: New York, NY, US

Re: JS timer help

Post 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.
(#10850)
Post Reply