Advertisement
If you have a new account but are having problems posting or verifying your account, please email us on hello@boards.ie for help. Thanks :)
Hello all! Please ensure that you are posting a new thread or question in the appropriate forum. The Feedback forum is overwhelmed with questions that are having to be moved elsewhere. If you need help to verify your account contact hello@boards.ie
Hi there,
There is an issue with role permissions that is being worked on at the moment.
If you are having trouble with access or permissions on regional forums please post here to get access: https://www.boards.ie/discussion/2058365403/you-do-not-have-permission-for-that#latest

Multiple Javascript counters (time)

  • 26-03-2010 12:58am
    #1
    Moderators Posts: 12,395 ✭✭✭✭


    Ive got a Javascript function to display the current time on my webpage.

    What I would like to do is put in several other time displays, but this time counting down to 0.

    I currently have code to get the difference between now and a future time saved in the database and display that time in hours minutes and seconds, updating every second counting down.

    Separatly these codes work great, but put them together and either 1 (the 1st one) or the other works. I need to be able to run them and more countdowns at the same time on the same page.

    I wrecked my brain for so long getting this far and couldnt understand why it worked on its own, but not when I implemented it into my other page.:mad:

    Any help would be amazing.


Comments

  • Users Awaiting Email Confirmation Posts: 351 ✭✭ron_darrell


    Problem is with the timeouts or intervals you're using - as far as I know the browser can only handle one on a page. What you need to do is come up with a single timeout/interval that updates all your counters at the same time (though at different rates if that's what you require). Can you post your code so we can see what you've done so far and maybe we can suggest an alternative way of doing it?

    Regards,
    RD


  • Closed Accounts Posts: 4 cistov


    Note: you can have multiple intervals running at the same time. We'd need to look at the code to advise something more specific.


  • Moderators Posts: 12,395 ✭✭✭✭Black_Knight


    current time:
    <p class="time">
    <script type="text/javascript">
    
    var currenttime = '<? print date("F d, Y H:i:s", time())?>' //PHP method of getting server date
    
    ///////////Stop editting here/////////////////////////////////
    
    var montharray=new Array("January","February","March","April","May","June","July","August","September","October","November","December")
    var serverdate=new Date(currenttime)
    
    function padlength(what){
    var output=(what.toString().length==1)? "0"+what : what
    return output
    }
    
    function displaytime(){
    serverdate.setSeconds(serverdate.getSeconds()+1)
    var datestring=montharray[serverdate.getMonth()]+" "+padlength(serverdate.getDate())+", "+serverdate.getFullYear()
    var timestring=padlength(serverdate.getHours())+":"+padlength(serverdate.getMinutes())+":"+padlength(serverdate.getSeconds())
    document.getElementById("servertime").innerHTML=datestring+" "+timestring
    }
    
    window.onload=function(){
    setInterval("displaytime()", 1000)
    }
    
    </script>
    
    <span id="servertime"></span>
    </p>
    

    Countdown clock:
    <html>
    <head></head>
    <body>
    <?php
    // SOME SQL HERE TO GET A TIME STORED IN THE DB
    
    	$time = (strtotime(date("F j, Y, g:i:s a", $result)) - strtotime(date('F j,Y, g:i:s a')));
    
    	?>
    
    
    	<script type="text/javascript">
    	window.onload = function() {
    	/*	set your parameters(
    	number to countdown from, 
    	pause between counts in milliseconds, 
    	function to execute when finished
    	) 
    	*/
    	var time = "<?php echo $time;?>"
    	startCountDown(time, 1000, myFunction);
    	}
    
    	function startCountDown(i, p, f) {
    	//	store parameters
    	var pause = p;
    	var fn = f;
    	//	make reference to div
    	var countDownObj = document.getElementById("countDown");
    	if (countDownObj == null) {
    	//	error
    	alert("div not found, check your id");
    	//	bail
    	return;
    	}
    	countDownObj.count = function(i) {
    	//	write out count
    
    	function cheat2(secs)
    	{
    	var t = new Date(1970,0,1);
    	t.setSeconds(secs);
    	var s = t.toTimeString().substr(0,8);
    	if(secs > 86399)
    	s = Math.floor((t - Date.parse("1/1/70")) / 3600000) + s.substr(2);
    	return s;
    	}
    	var timeleft;
    	timeleft = cheat2(i);
    
    	countDownObj.innerHTML = timeleft;
    	if (i == 0) {
    	//	execute function
    	fn();
    	//	stop
    	return;
    	}
    	setTimeout(function() {
    	//	repeat
    	countDownObj.count(i - 1);
    	},
    	pause
    	);
    	}
    	//	set it going
    	countDownObj.count(i);
    	}
    
    	function myFunction() {
    	alert("Item Ended!");
    	}
    
    	var currenttime = '<? echo time("F d, Y H:i:s", $time)?>'
    	</script>
    	
    		
            <div id="countDown"></div>
    </body>
    </html>
    


    Both are as includes into my index.php page, but when I include the countdown (on its own) to a blank framed page the countdown doesnt work. To make it work, I MUST include the javascript function from the Countdown clock, into my blank framed page. At which point I can remove the javascript function from the Countdown clock code. Sorry, thats the best way I can describe it.


  • Closed Accounts Posts: 4 cistov


    Initialiser functions for both timers are attached to window.onload which can only fire one function by default. You can use something like this to get around that:
    function addLoadEvent(func) {
    	var oldonload = window.onload;
    	if (typeof window.onload != 'function') {
    		window.onload = func;
    	}
    	else {
    		window.onload = function() {
    			oldonload();
    			func();
    		}
    	}
    }
    
    // other code here
    
    addLoadEvent(function(){
    	setInterval(displaytime, 1000)
    });
    
    // other code here
    
    addLoadEvent(function() {
    	var time = "<?php echo $time;?>"
    	startCountDown(time, 1000, myFunction);
    });
    


  • Moderators Posts: 12,395 ✭✭✭✭Black_Knight


    Right. That worked oh so well!

    Now my problem is, I need multiples of that Countdown timer, which will display different countdowns.

    ATM, I have a loop which runs through the top 5 rows in the DB and displays details about them, and also returns a future date/time.

    The current time is taken away from this and stored in a variable $time (as above). This is repeated in a loop to give each elements remaining time.
    The only problem being, they are all writing to the same countdown output.

    Can I set up an array of the countdown outputs to display them all?

    Thank a million guys, yer saving me a world of frustration!


  • Advertisement
  • Closed Accounts Posts: 18,163 ✭✭✭✭Liam Byrne


    Problem is with the timeouts or intervals you're using - as far as I know the browser can only handle one on a page.

    Completely incorrect - you can use as many as you want, and if you code it right you can even get them to interact.


  • Closed Accounts Posts: 18,163 ✭✭✭✭Liam Byrne


    The only problem being, they are all writing to the same countdown output.

    Which is precisely what you have coded it to do
    document.getElementById("countDown");
    

    Assuming that the "i" in the function call "startCountDown(i,p,f)" is an integer for the counter number (I could be wrong here), your required code would be
    document.getElementById("countDown"+i);
    


  • Moderators Posts: 12,395 ✭✭✭✭Black_Knight


    Yes, i is the count that it starts from, which would change for each $temp I pass to the function.

    What does changing it from i to "countdown"+i do?

    I through in "countdown"+i, moved the script into the loop and ran the code, but it didnt make a difference.

    Im a bit of a puppet at this stage. It my first time working with javascript so im pretty useless ATM.


  • Closed Accounts Posts: 4 cistov


    You'd populate the times array via PHP.

    In the original code count function was attached to DOM node, which can lead to memory leaks, so I've just defined it as a local variable instead.

    Hope this helps.
    <script type="text/javascript">
    
    function addLoadEvent(func) {
    	var oldonload = window.onload;
    	if (typeof window.onload != 'function') {
    		window.onload = func;
    	}
    	else {
    		window.onload = function() {
    			oldonload();
    			func();
    		}
    	}
    }
    
    var times = [001, 5602, 78022, 22036, 550040];
    var idprefix = "countDown";
    var interval = 1000;
    
    addLoadEvent(function () {
    	for(var i = 0; i < times.length; i++) {
    		startCountDown(times[i], interval, myFunction, idprefix + i);
    	}
    });
    
    function getTimeString(secs) {
    	var t = new Date(1970, 0, 1);
    	t.setSeconds(secs);
    	var s = t.toTimeString().substr(0, 8);
    	if (secs > 86399) s = Math.floor((t - Date.parse("1/1/70")) / 3600000) + s.substr(2);
    	return s;
    }
    		
    function startCountDown(timeleft, pause, fn, id) {
    
        //	make reference to div
        var countDownObj = document.getElementById(id);
        if (!countDownObj) { alert("div not found, check your id"); return; }
    	
        var count = function(timeleft) {
            //	write out count
            countDownObj.innerHTML = getTimeString(timeleft);
            if (timeleft == 0) {
                //	execute function
                fn(countDownObj);
                //	stop
                return;
            }
            setTimeout(function () {
                //	repeat
                count(timeleft - 1);
            },
            pause);
        }
        //	set it going
        count(timeleft);
    }
    
    function myFunction(countDownObj) {
    	countDownObj.innerHTML = "00:00:00";
    }
    </script>
    	
    
    <div id="countDown0"></div>
    <div id="countDown1"></div>
    <div id="countDown2"></div>
    <div id="countDown3"></div>
    <div id="countDown4"></div>
    


  • Moderators Posts: 12,395 ✭✭✭✭Black_Knight


    Excellent Stuff lads! Really appreciate it!

    Now if only I could turn back time a backup all my data. Theres 3 of us working on the project... someone overwrote a load of my work. Nothing to do with this thread, but a damn pain in the ass.

    Thatll teach me :rolleyes:


  • Advertisement
  • Registered Users, Registered Users 2 Posts: 26,584 ✭✭✭✭Creamy Goodness


    Excellent Stuff lads! Really appreciate it!

    Now if only I could turn back time a backup all my data. Theres 3 of us working on the project... someone overwrote a load of my work. Nothing to do with this thread, but a damn pain in the ass.

    Thatll teach me :rolleyes:
    how come you aren't all using some form of version control?


  • Moderators Posts: 12,395 ✭✭✭✭Black_Knight


    Because we're idiots! Obviously!


Advertisement