Clock in Javascript - javascript

I have made a clock in javascript but its a static clock. What changes I need to do in the following code so that it updates with every second.
<html>
<head>
<title>Javascript Clock</title>
<script type="text/javascript">
function clk() {
var a=new Date();
document.getElementById("disp").innerHTML=a.getHours() + ":" + a.getMinutes() + ":" + a.getSeconds() ;
}
</script>
</head>
<body>
<input type="button" onclick="clk()" value="Display Clock" />
<p id="disp">Clock Space</p>
</body>
</html>

You can use setInterval to run your clk() function every second:
setInterval(clk, 1000); // run clk every 1000ms
MDN on setInterval
As nnnnnn points out, the timer interval probably won't be synchronized with the passage of an actual, real-time second, so using an interval like 100ms might not be a bad idea.

You can add setTimeout(clk,1000); to your function,as bellow:
function clk() {
var a=new Date();
document.getElementById("disp").innerHTML=a.getHours() + ":" + a.getMinutes() + ":" + a.getSeconds() ;
setTimeout(clk,1000);
}

A JavaScript digital clock from system time, can also manually set. :-)
function timer(h,m,s){
var sec;
var min;
var hrs;
var day;
if(((s<=59) && (s>=0)) && ((m<=59) && (m>=0)) && ((h<=23) && (h>=0))){
sec=s;
min=m;
hrs=h;
//set parent element id 'lga' to your id
var parent = document.getElementById('lga');
parent.innerHTML = '';
var child = document.createElement('div');
child.id = "thanesh";
child.style = 'font-size:20px';
parent.appendChild(child);
setInterval(function(){
sec++;
if(sec==60){sec=0;min++;}
if(min==60){min=0;hrs++;}
if(hrs==24){hrs = 0; min = 0; sec = 0;}
if(hrs<=12){
day = 'AM';
}else{
day = 'PM';
}
document.getElementById('thanesh').innerHTML = '<table style="background-color:#f5f5f5;"><tr><td><div id="hh">0</div><td>'
+hrs+' : <td><div id="mm">0</div><td>'
+min+' : <td><div id="ss">0</div><td>'
+sec+' <td>'
+day+'</td></td></td></td></td></td></td></tr></table>';
if(sec>9){
document.getElementById('ss').style.display = "none";
}else if(sec==0){
document.getElementById('ss').style.display = "block";
}
if(min>9){
document.getElementById('mm').style.display = "none";
}else if(min==0){
document.getElementById('mm').style.display = "block";
}
if(hrs>9){
document.getElementById('hh').style.display = "none";
}else if(hrs==0){
document.getElementById('hh').style.display = "block";
}
},
1000);
}else{
alert("Check time inputs...!");
}
}
//Set Hour, Minutes, Seconds by JS / manually
var date = new Date();
var hst = date.getHours();
var mst = date.getMinutes();
var sst = date.getSeconds();
timer(hst,mst,sst);

Since your "update every second" of the real clock competes with other computer tasks, the delay before the next real clock tic will be less than 1000 ms very often. So, better use setTimeout instead of setInterval. In fact, we just need to twist a little bit the end of the denied 姚先进's solution here arround, resulting in:
function clk() {
var a=new Date();
document.getElementById("disp").innerHTML=a.getHours() + ":" + a.getMinutes() + ":" + a.getSeconds() ;
setTimeout(clk, 1000 - a % 1000);
}
This is my clock solution since 2007.

here we go
<html>
<head>
<title>Javascript Clock</title>
<script type="text/javascript">
function clk() {
setInterval(() => {
var a = new Date();
document.getElementById("disp").innerHTML = a.getHours() + ":" + a.getMinutes() + ":" + a.getSeconds();
},1000);
}
</script>
</head>
<body>
<input type="button" onclick="clk()" value="Display Clock" />
<p id="disp">Clock Space</p>
</body>
</html>

Related

onclick fires with no issues but addEventListener requires multiple clicks to work

I've tried this a few different ways. I'm attempting to create an event for a button that toggles an elements visibility on and off. for some reason when I use .onclick it works fine. Each time I click the button it toggles the element visibility as expected. However when I attempt to swap .onClick for addEventListener the button has to be clicked multiple times for it to work. It seems intermittent. It may work on the 1st click one time and then the next time it may require 2 or 3.
function showTime() {
options = {weekday: 'short', year: 'numeric', month: 'short', day: '2-digit'}
var date = new Date();
var hr = date.getHours();
var min = date.getMinutes();
var sec = date.getSeconds();
var period = "am";
if(hr == 0){
hr = 12;
}
if(hr > 12){
hr = hr - 12;
period = "pm";
}
min = (min < 10) ? "0" + min : min;
sec = (sec < 10) ? "0" + sec : sec;
var time = hr + ":" + min + ":" + sec + " " + period;
document.getElementById("displayTime").innerHTML = time;
document.getElementById("displayDate").innerHTML = date.toLocaleDateString("en-US", options);
var startTime = setTimeout(showTime, 1000);
//Set Alarm
var set = document.getElementById("setButton");
set.onclick = function(){
var timeVis = document.getElementById("displayTime");
if (timeVis.style.display !== 'none') {
timeVis.style.display = 'none';
} else {
timeVis.style.display = 'block';
}
}
}
showTime();
<!DOCTYPE html>
<html lang = "en">
<head>
<meta charset="utf-8"/>
<title> Clock </title>
</head>
<body>
<div id="displayTime" onLoad="showTime()" ></div>
<input type="text" id="setInput">
<button id="setButton">set</button>
<div id="displayDate"></div>
<script src="DigitalClock.js"></script>
</body>
</html>
Below are the two alternate ways I attempted to use add an event listener
var set = document.getElementById("setButton");
set.addEventListener('click', function(){
var timeVis = document.getElementById("displayTime");
if (timeVis.style.display !== 'none') {
timeVis.style.display = 'none';
} else {
timeVis.style.display = 'block';
}
});
var set = document.getElementById("setButton");
var timeVis = document.getElementById("displayTime");
function vis(){
if (timeVis.style.display !== 'none') {
timeVis.style.display = 'none';
} else {
timeVis.style.display = 'block';
}
};
timeVis.addEventListener('click', vis);
The problem is that you use addEventListener inside the showTime() function, so each time showTime() is executed, you bind a new listener.
Now because of this:
var startTime = setTimeout(showTime, 1000);
The function is executed each second. As a result, after a couple of seconds, when you click one time on the button, the toggle part is executed multiple times.
On the other hand, with set.onclick, you only redefine the onclick property of the element, this is why it's working as expected.

How to I auto-update a clock in Javascript? [duplicate]

This question already has answers here:
Run JavaScript function at regular time interval
(4 answers)
setInterval using a non anonymous function requiring parameters has to be inside an anonymous function. Why?
(4 answers)
Closed 6 years ago.
I am trying to make a simple web based clock app using pure java-script. I think the general code is right, but I'm not sure how to automatically call the function at a set interval of time. I thought the window.onload, followed by the setInterval method would do this. But it's not automatically updating every half second as I expected. What am I doing wrong?
<!doctype html>
<html>
<head>
<title>Real Time Clock</title>
<script>
var time, h, m, s, track;
track = 0;
window.onload = function() { setInterval( timeNow(), 100); }
function timeNow() {
time = new Date();
track += 1;
h = time.getHours();
m = time.getMinutes();
s = time.getSeconds();
if ( s < 10 ) { s = "0" + s; } /* we add a 0 in front of s, when it is lower than 10, because that's what most clocks display, this is for the human user rather than for any need by the computer */
document.getElementById("time").innerHTML = h + ':' + m + ':' + s;
document.getElementById("track").innerHTML = track;
}
</script>
</head>
<body>
<span id="time">~Waiting for time update.</span><br>
<span id="track"></span>
</body>
</html>
Seems to work fine. Just needed to change
window.onload = function() { setInterval( timeNow(), 100); }
to
window.onload = function() { setInterval( timeNow, 100); }
<!doctype html>
<html>
<head>
<title>Real Time Clock</title>
<script>
var time, h, m, s, track;
track = 0;
window.onload = function() { setInterval( timeNow, 100); }
function timeNow() {
time = new Date();
track += 1;
h = time.getHours();
m = time.getMinutes();
s = time.getSeconds();
if ( s < 10 ) { s = "0" + s; } /* we add a 0 in front of s, when it is lower than 10, because that's what most clocks display, this is for the human user rather than for any need by the computer */
document.getElementById("time").innerHTML = h + ':' + m + ':' + s;
document.getElementById("track").innerHTML = track;
}
</script>
</head>
<body>
<span id="time">~Waiting for time update.</span><br>
<span id="track"></span>
</body>
</html>
use setInterval(timeNow,100); instead of setInterval(timeNow(),100);
var time, h, m, s, track;
track = 0;
window.onload = function() {
var start = setInterval(timeNow,100);
}
function timeNow() {
var time = new Date();
track += 1;
h = time.getHours();
m = time.getMinutes();
s = time.getSeconds();
if ( s < 10 ) { s = "0" + s; }
document.getElementById("time").innerHTML = h + ':' + m + ':' + s;
document.getElementById("track").innerHTML = track;
}
<span id="time">~Waiting for time update.</span><br>
<span id="track"></span>
You are passing an undefined (as the result of calling timeNow) to setInterval. You need to pass the function, so the code will be:
window.onload = function() { setInterval(timeNow, 100); }

Format time to minutes and seconds in countdown/timer

I am building a pomodoro clock/countdown, but have an issue with formatting selected time to minutes/hours/seconds. I have tried to multiply the secs variable with 60 (secs*=60), but it makes a mess and I can't figure out how to fix it. So, I would like it to "know" that it needs to count down from 25 minutes - in 25:00 format, or more/less(hh:mm:ss) if the user chooses so with + and - buttons. All help very appreciated
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
</head>
<body>
<h1 id="num">25 min</h1>
<div id="status"></div>
<button onclick='countDown(secs, "status")'>Start countdown</button>
<button onclick='increaseNumber()'>+</button>
<button onclick='decreaseNumber()'>-</button>
<script src="script.js"></script>
</body>
</html>
and here is javascript:
var num = document.getElementById('num').innerHTML;
var secs = parseInt(num);
function countDown(secs, elem) {
var element = document.getElementById(elem);
secs--;
var timer = setTimeout(function() {
countDown(secs, elem);
}, 1000);
//secs *= 60;
if(secs%60 >= 10){ //10 - if it's not a single digit number
document.getElementById('num').innerHTML = (Math.floor(secs/60) + ":" + secs%60);
}
else{
document.getElementById('num').innerHTML = (Math.floor(secs/60) + ":" + "0" + secs%60);
}
element.innerHTML = "Please wait for "+secs+" minutes";
//if timer goes into negative numbers
if(secs < 1){
clearTimeout(timer);
element.innerHTML = '<h2>Countdown complete!</h2>';
element.innerHTML += 'Click here now';
}
}
function increaseNumber() {
secs += 5;
document.getElementById('num').innerHTML = secs + ' min';
}
function decreaseNumber() {
if(secs >= 10) {
secs -= 5;
document.getElementById('num').innerHTML = secs + ' min';
}
}
Is there a reason you're doing it by hand ?
If you don't mind using a library, moment.js does a very good job at time manipulations. It's lightweight and very easy to use.
If you have to do it by hand because of some limitations, what are they ?
For reference:
//Creates a moment. Its value is the time of creation
var timer = moment();
//add 60 seconds to the timer
timer.add(60, 's');
//Removes 1 minutes from the timer
timer.subtract(1, 'm');
Sources :
Add
Substract
Try this countDown function:
function countDown(secs, elem) {
var element = document.getElementById(elem);
element.innerHTML = "Please wait for "+secs+" minutes";
var second = 0;
var timer = setInterval(function(){
var extraZero = second < 10 ? '0' : '';
document.getElementById('num').innerHTML = secs + ":" + extraZero + second;
if (second-- === 0) {
second = 59;
if (secs-- === 0){
clearInterval(timer);
element.innerHTML = '<h2>Countdown complete!</h2>';
element.innerHTML += 'Click here now';
}
}
}, 1000);
}
Since you are counting down the seconds, it is making more sense to use setInterval instead of setTimeout.

Forcing page refresh at a specific time with timezone

I'm trying to force a page to refresh with js at a specific time, after digging around I found the script below. However, it doesn't appear to take into consideration timezones. How would I implement that?
<html>
<head>
<title></title>
<script type="text/javascript">
function refreshAt(hours, minutes, seconds) {
var now = new Date();
var then = new Date();
if(now.getHours() > hours ||
(now.getHours() == hours && now.getMinutes() > minutes) ||
now.getHours() == hours && now.getMinutes() == minutes && now.getSeconds() >= seconds) {
then.setDate(now.getDate() + 1);
}
then.setHours(hours);
then.setMinutes(minutes);
then.setSeconds(seconds);
var timeout = (then.getTime() - now.getTime());
setTimeout(function() { window.location.reload(true); }, timeout);
}
refreshAt(15,06,0); //Will refresh the page at 3:06pm
</script>
</head>
<body onLoad="setInterval('getCurrentTime()', 1000);">
<div id="time"></div>
content
</body>
</html>
Here you go, reload will occur for every user exactly as you define in global vars in script:
EDIT!!! I had bug in code so I have updated the script...
EDIT working example:
http://simplestudio.rs/yard/tinediffredir/content.html
<html>
<head>
<title>Chk diff and reload if match</title>
<script>
var reload_time = "15060"; // this is 15:06:00 - change to desired reload time
var reload_hour_diff = 15; // for cheking diff - change to desired hours
var reload_minute_diff = 6; // for cheking diff - change to desired minutes
var time_zone_offset = "-5"; // globally looking from GMT time, change this according to DST
var reload_time_checker = setInterval(function(){reload_page()},300);
var diff = null;
function chk_reload_moment(offset) {
dat = new Date();
utc = dat.getTime() + (dat.getTimezoneOffset() * 60000);
default_date = new Date(utc + (3600000*offset));
var default_year = default_date.getFullYear();
var default_month = default_date.getMonth();
var default_day = default_date.getDate();
var default_hour = default_date.getHours();
var default_minutes = default_date.getMinutes();
var default_seconds = default_date.getSeconds();
user_date = new Date();
var user_year = user_date.getFullYear();
var user_month = user_date.getMonth();
var user_day = user_date.getDate();
var user_hour = user_date.getHours();
var user_minutes = user_date.getMinutes();
var user_seconds = user_date.getSeconds();
user_current = user_hour+""+user_minutes+""+user_seconds;
default_current_f = default_day+"/"+default_month+"/"+default_year+" "+default_hour+":"+default_minutes+":"+default_seconds;
user_current_f = user_day+"/"+user_month+"/"+user_year+" "+user_hour+":"+user_minutes+":"+user_seconds;
var timeEnd = new Date(user_current_f);
var timeEndH = timeEnd.getHours();
var timeEndM = timeEnd.getMinutes();
var new_reload_minute_diff = 60+reload_minute_diff;
diff = (timeEndH - reload_hour_diff + 12) + " hours " + (new_reload_minute_diff - timeEndM) + " minutes";
if (user_current == reload_time) {
return true;
}
else {
return false;
}
}
function reload_page() {
var chktime = chk_reload_moment(time_zone_offset);
if (chktime) {
window.location.reload();
}
else {
var timer_div = document.getElementById('timer');
timer_div.innerHTML = "remaining: " + diff + " until new content";
}
}
</script>
</head>
<body>
<div id="timer">
</div>
</body>
</html>
I think it is clear how to configure it but if you have some problems feel free to ask...

JavaScript Clock won't display correctly

I've been teaching myself JavaScript and i'm still fairly new, i've tried to make a clock feature to add to my site, however, I can't see to get it to display, this is my full code:
<html>
<head>
<script type="text/javascript">
function tick() {
var hours, minutes, seconds, ap;
var intHours, intMinutes, intSeconds;
var today;
today = new Date();
intHours = today.getHours();
intMinutes = today.getMinutes();
intSeconds = today.getSeconds();
if (intHours == 0) {
hours = "12:";
ap = "Midnight";
} else if (intHours < 12) {
hours = intHours + ":";
ap = "a.m";
} else if (intHours == 12) {
hours = "12:";
ap = "noon";
} else {
intHours = intHours - 12
hours = intHours + ":";
ap = "p.m.";
}
if (intMinutes < 10) {
minutes = "0" + intMinutes + ":";
} else {
minutes = intMinutes + ":";
}
if (intSeconds < 10) {
seconds = "0" + intSeconds + " ";
} else {
seconds = intSeconds + " ";
}
timeString = hours + minutes + seconds + ap;
Clock.innerHTML = timeString;
window.setTimeout("tick();", 100);
}
//--></script>
</head>
<body>
<div id="Clock" align="center" style="font-family: Verdana; font-size: 10px; color:#000000"></div>
</body>
</html>
As I said, I run it and as far as I can see, it should run fine, as I said i'm a bit new, so maybe someone could help me out.
Thanks again people.
EDIT: Before anyone says, I am fully aware that there are premade working examples of this kind of thing, such as jQuery clocks etc, but I wanted to make one myself from scratch.
It is not starting, mainly because you need to call the function at least once initially:
tick();
Where ever you are learning HTML and JavaScript from, stop learning from there immediately; the code habits and methods you are learning are very, very poor and outdated.
Problems include:
not having a DOCTYPE: <!DOCTYPE html>
accessing div#Clock as a global variable Clock, which is deprecated, and should be document.getElementById('Clock');
using a string to setTimeout, when it should really be setTimeout(tick, 100);
using the deprecated align attribute, when you should use text-align: center; in CSS
using the 'old-browser' JavaScript comment-out trick
using inline CSS via the style attribute, which constitutes poor separation of presentation and content
First, you need to run your function tick() somewhere. It doesn't do anything if you only define it. In the body onLoad event for example.
Second, your element should be properly set in a var. You should get the element by id:
var Clock = document.getElementById('Clock');
Just change your last two lines from
window.setTimeout("tick();", 100);
}
to
}
window.setInterval(tick, 1000);
Demo: http://jsfiddle.net/naveen/3PQ8B/1/
Update: missed the document.getElementById part :)
<html>
<head>
<script type="text/javascript">
function startTime()
{
var today=new Date();
var h=today.getHours();
var m=today.getMinutes();
var s=today.getSeconds();
// add a zero in front of numbers<10
m=checkTime(m);
s=checkTime(s);
document.getElementById('txt').innerHTML=h+":"+m+":"+s;
t=setTimeout('startTime()',500);
}
function checkTime(i)
{
if (i<10)
{
i="0" + i;
}
return i;
}
</script>
</head>
<body onload="startTime()">
<div id="txt"></div>
</body>
</html>

Categories