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.

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

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

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

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

Be a part of the DaniWeb community

We're a friendly, industry-focused community of developers, IT pros, digital marketers, and technology enthusiasts meeting, networking, learning, and sharing knowledge.