Bem, hoje comecei a aprender javascript e como primeiro programa decidi fazer um relógio que achasse ser o mais eficiente possível. Este foi o resultado final:
// JavaScript Document
// clock.js a clock that update only when it's really required and what is required.
// What i mean with this is that for exemplo at the time 10:11:00 the clock just update the seconds and the minutes, not que hours.
// the close doesn't update at a fixed time like almost every clocks, just update when the output is different form the actual output
//
// Author: João Santos (jarsantos@gmail.com)
//
// Everyone can use it and change it, but keep the credits please
// Enjoy!
var weekDays = new Array("Sunday", "Monday", "Thursday", "Wednesday", "Tuesday", "Friday", "Saturday")
var months = new Array("January", "February", "March", "April", "May", "June", "July", "August", "September", "October", "November", "December")
function formatClock(int)
{
if(int < 10)
{
int = '0'+int
}
return int
}
function startClock()
{
var date = new Date()
var time = new Array(date.getHours(), formatClock(date.getMinutes()), formatClock(date.getSeconds()))
var weekDay = date.getDay()
var month = date.getMonth()
var day = new Array(weekDay, weekDays[weekDay], date.getDate(), month, months[month], date.getFullYear())
return new Array(time, day)
}
function updateClock(passado)
{
time = passado[0]
day = passado[1]
clockInfo = passado[2]
date = new Date()
time[2] = formatClock(date.getSeconds())
if(time[2] == '00')
{
time[1] = formatClock(date.getMinutes())
if(time[1] == '00')
{
time[0] = date.getHours()
if(time[0] == 0)
{
day[0] = date.getDay()
day[1] = weekDays[day[0]]
day[2] = date.getDate()
if(day[2] == 1)
{
day[3] = date.getMonth()
day[4] = months[day[3]]
if(day[3] == 1)
{
day[5] = date.getFullYear();
}
}
}
}
}
document.getElementById('clock').innerHTML=time.join(':')+'<br />'+day[1]+', '+day[2]+' '+day[4]+' '+day[5]
t=setTimeout('updateClock(new Array(time, day))',1000-(new Date().getMilliseconds()))
}
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<html xmlns="http://www.w3.org/1999/xhtml">
<head>
<meta http-equiv="Content-Type" content="text/html; charset=utf-8" />
<title>Clock Test</title>
<script type="text/javascript" src="clock.js"></script>
</head>
<body onload="updateClock(startClock())">
<div id="clock"></div>
</body>
</html>
Espero que gostem, deu-te um grande trabalho, mas também é um gozo ver o programa a trabalhar tão bem.
Se testarem ao lado do que já foi colocado aqui neste tópico vão ver que este é mais rápido a actualizar e mais eficiente (não usa tanto o CPU)