0

I have a javascript that displays a countdown in the browser. The problem is that if the element does not load immediately the countdown turns to negative. Here is the script:

<script>
var time = 10; //How long (in seconds) to countdown
var page = '<?php echo $page ?>'; //The destination.
function countDown(){
time --;
get("message").innerHTML = time;
if(time == 0){
window.location = page;
}
}
function get(id){
if(document.getElementById) return document.getElementById(id);
if(document.all) return document.all.id;
if(document.layers) return document.layers.id;
if(window.opera) return window.opera.id;
}
function init(){
if(get('message')){
setInterval(countDown, 1000);
get("message").innerHTML = time;
}
else{
setTimeout(init, 50);
}
}
document.onload = init();
</script>

Will someone please help? I just need a way to tell the countdown to stop at 0. Thanks.

3
Contributors
4
Replies
5
Views
7 Years
Discussion Span
Last Post by Airshow
0

This should do the trick:

<script type="text/javascript">
var time = 10; //How long (in seconds) to countdown
var page = 'ddd.html'; //The destination.
var myInterval;
function countDown(){
time --;
get("message").innerHTML = time;
if(time == 0){
window.location = page;
clearInterval(myInterval);
time = 10;
}
}
function get(id){
if(document.getElementById) return document.getElementById(id);
if(document.all) return document.all.id;
if(document.layers) return document.layers.id;
if(window.opera) return window.opera.id;
}
function init(){
if(get('message')){
myInterval = setInterval(countDown, 1000);
get("message").innerHTML = time;
}
else{
setTimeout(init, 50);
}
}
document.onload = init();
</script>

~G

0

Tekkno,

The code can be made much simpler by framing the whole thing inside one function, for example an anonymous window.onload function, like this:

var $ = function(id){ return (document.getElementById) ? document.getElementById(id) : (document.all) ? document.all[id] : (document.layers) ? document.layers[id] : (window.opera) ? window.opera[id] : null; }
window.onload = function(){
	var msg = $("message");
	if(msg){
		var time = msg.innerHTML = 10; //How long (in seconds) to countdown
		var tim = setInterval(function(){
			msg.innerHTML = --time;
			if(time <= 0){
				clearInterval(tim);
				window.location = '<?php echo $page ?>';
			}
		}, 1000);
	}
};

Airshow

Edited by Airshow: n/a

0

Thank you both. Airshow, I went with your solution being that the code is more condensed. It works like a charm.

0

Tekkno,

The key is clearInterval() .

It may be easier to see exactly how it works in Graphix' code, which does exactly the same as mine.

Airshow

This question has already been answered. Start a new discussion instead.
Have something to contribute to this discussion? Please be thoughtful, detailed and courteous, and be sure to adhere to our posting rules.