Digital clock continuously updating time


(jangeltun) #1

I’ve made a clock that is functional within an iFrame, but I can’t get it to continuously update the time without an iFrame. Any ideas?

javascript clock.zip (23.7 KB)


(Mark Hunte) #2

You initial problem is not understanding the code and what it does.

A time out will fire its code after a give time.
In the widget it calls a function which happens to be the main function itself.

But in the Hype function that does not exist.

You could fix this a number of ways.

1, Use the exact same code in a Hype Function but add the initial call to the startTime() function.

startTime()
	
function startTime() {
    var today = new Date();
    var h = today.getHours();
    var m = today.getMinutes();
    var s = today.getSeconds();
    m = checkTime(m);
    s = checkTime(s);
    document.getElementById('txt2').innerHTML = h + ":" + m + ":" + s+" "+(h<12?"AM":"PM");
    var t = setTimeout(startTime, 500);
}
function checkTime(i) {
    if (i < 10) {i = "0" + i};  // add zero in front of numbers < 10
    return i;
}

2, Use a setInterval

 setInterval(function(){ 

var today = new Date();
	var h = today.getHours();
	var m = today.getMinutes();
	var s = today.getSeconds();
	m = checkTime(m);
	s = checkTime(s);
	document.getElementById('txt2').innerHTML = h + ":" + m + ":" + s+" "+(h<12?"AM":"PM");

 }, 500);
   
 


function checkTime(i) {
    if (i < 10) {i = "0" + i};  // add zero in front of numbers < 10
    return i;
}

You probably want to use a setInterval instead.

You need to read up on the code you are using. Just pasting one bit of code else where does not always work as you have discovered.


(jangeltun) #3

Thanks. setInterval works great. I’ve updated my sample.

javascript clock v3.hype.zip (29.4 KB)


(𝕄𝕚𝕔𝕙𝕒𝕖𝕝 𝔾𝕒𝕣𝕠𝕗𝕒𝕝𝕠) #4

I’m thinking you don’t need the “checkTime” function. The “slice” method might be easier. Here’s a sample line of code from A Book About Hype - the “Timing” example…

hypeDocument.getElementById('ss').innerHTML = ("0" + now.getSeconds()).slice(-2);​

A zero is appended to the front. If it’s not needed, it gets sliced off.