Javascript clock update on the minute help? - javascript

ok i have a cool digital clock and javascript but i cant get it to update every minute, help?
<html>
<head>
<style type="text/css">
#font-face {
font-family: Digital;
src: url('digital.ttf');
}
html {
font-family: "Digital";
font-size: 130px;
}
#clock {
color: red;
}
</style>
<script type="text/javascript" language="JavaScript">
function getClockTime()
{
var now = new Date();
var hour = now.getHours();
var minute = now.getMinutes();
if (hour > 12) { hour = hour - 12; }
if (hour == 0) { hour = 12; }
if (minute < 10) { minute = "0" + minute; }
var timeString = hour +
':' +
minute
return timeString;
}
</script>
</head>
<body bgcolor="#000;" onload="init();">
<p id="clock" align="center">hi</p>
<script type="text/javascript" language="JavaScript"><!--
var clockTime = getClockTime();
document.getElementById('clock').innerHTML = clockTime;
</script>
<script type=text/javascript>
function init()
{
getClockTime();
window.setInterval(getClockTime,30000);
}
</script>
</body>
</html>

You are better off to use consecutive setTimeout calls and calcualte the time to wait each time. setInterval is not guaranteed to run at exactly the time you specify, so the clock will slowly drift. Also, if the user doesn't start it exactly on a whole minute, the clock will update out of sync with the system clock.
A modified init function is below that will call the clock setting function about 5ms after the next whole minute each and every time.
function init()
{
var interval = (60 - (new Date()).getSeconds()) * 1000 + 5;
getClockTime();
setTimeout(init,interval);
}

<html>
<head>
<style type="text/css">
#font-face {
font-family: Digital;
src: url('digital.ttf');
}
html {
font-family: "Digital";
font-size: 130px;
}
#clock {
color: red;
}
</style>
<script type="text/javascript" language="JavaScript">
function getClockTime()
{
var now = new Date();
var hour = now.getHours();
var minute = now.getMinutes();
var second = now.getSeconds();
if (hour > 12) { hour = hour - 12; }
if (hour == 0) { hour = 12; }
if (minute < 10) { minute = "0" + minute; }
var timeString = hour +
':' +
minute +
':' +
second
document.getElementById('clock').innerHTML = timeString;
}
</script>
</head>
<body bgcolor="#000;" onload="init();">
<p id="clock" align="center">hi</p>
<script type="text/javascript" language="JavaScript"><!--
var clockTime = getClockTime();
</script>
<script type=text/javascript>
function init()
{
getClockTime();
setInterval(getClockTime,1000);
}
</script>
</body>
</html>

This line does nothing as you never accept the return value :
return timeString;
Instead use that to set the value of your
document.getElementById("clock").innerHTML = timeString;

A nifty regex will do the trick. Do, however, understand that the functions setTimeout and setInterval are highly unreliable for correctly managing time.
$('#clock').ready(function(){
var updateClock = function(){
var time = (new Date()).toString().match(/ (\d\d:\d\d):\d\d/);
$('#clock').text(time[1]);
};
setInterval(function(){
updateClock();
},60000);
updateClock();
});

This is my solution for react with hooks.
import { useState, useEffect } from "react";
export default function useTime() {
const [time, setTime] = useState(new Date());
useEffect(() => {
function getTime() {
let interval = (60 - new Date().getSeconds()) * 1000 + 5;
setTime(new Date());
setTimeout(getTime, interval);
}
getTime();
}, []);
return time;
}

I see two issues:
You are updating the clock every 30 seconds (30000 milliseconds). Is that intentional?
getClockTime will be called on the interval. Put document.getElementById('clock').innerHTML = timeString; as the last line of your function, and you should be good to go.

Added meridiem and post meridiem, fixed bug with seconds not having a preceding zero while less than 10 to #Rob 's answer
<html>
<head>
<style type="text/css">
#font-face {
font-family: Digital;
src: url('digital.ttf');
}
html {
font-family: "Digital";
font-size: 130px;
}
#clock {
color: red;
}
</style>
<script type="text/javascript" language="JavaScript">
function getClockTime()
{
var now = new Date();
var hour = now.getHours();
var minute = now.getMinutes();
var second = now.getSeconds();
var meridiem = "AM";
if (hour > 12) { hour = hour - 12; $meridiem = "PM" }
if (hour == 0) { hour = 12; }
if (minute < 10) { minute = "0" + minute; }
if (second < 10) { second = "0" + second; }
var timeString = hour +
':' +
minute +
':' +
second +
' ' +
meridiem
document.getElementById('clock').innerHTML = timeString;
}
</script>
</head>
<body bgcolor="#000;" onload="init();">
<p id="clock" align="center">hi</p>
<script type="text/javascript" language="JavaScript"><!--
var clockTime = getClockTime();
</script>
<script type=text/javascript>
function init()
{
getClockTime();
setInterval(getClockTime,1000);
}
</script>
</body>
</html>

setTimeout("location.reload(true);",timeoutPeriod)

Related

How to make "Start" button visible after clicking "Reset" button

I'm making a timer with jQuery. When you press the "Reset" button, it is supposed to make the "Start" button visible again.
I am getting this error:
Clicking the "Reset" button:
The selector "#reset" does not render the expected css for property "display": expected 'inline-block' to deeply equal 'none'
Here is my html:
<!DOCTYPE html>
<html lang="en">
<head>
<title>Interactivity</title>
<meta charset="utf-8"/>
<link rel="stylesheet" type="text/css" href="styles/site.css"/>
<script src="scripts/jquery-3.2.1.min.js"></script>
<script src="scripts/formatTime.js"></script>
<script src="scripts/times.js"></script>
<script src="scripts/reset.js"></script>
</head>
<body>
<div id="text">
<p>
Can you internally count 45 seconds precisely?
</p>
</div>
<button id="start">Start Timer</button>
<button id="stop" style="display: none;">Stop Timer</button>
<button id="reset" style="display: none;">Reset Timer</button>
<span id="time_started" class="hidden" style="display: none;">Timer Started</span>
<span id="time_ended" class="hidden">Timer Ended</span>
</body>
</html>
Here is my css:
body {
background-color: white;
font-family: sans-serif;
margin: 200px auto 0;
max-width: 900px;
}
h1 {
text-align: center;
}
div {
margin-bottom: 50px;
}
.hidden {
display: none;
}
Here is reset.js:
// reset everything
$("#reset").on('click',function() {
$(".results").addClass("hidden");
$("#reset").addClass("hidden");
$("#start").removeClass("hidden");
$("#time_started").addClass("hidden");
$("#time_ended").addClass("hidden");
});
Here is formatTime.js:
// formats the current date/time so that it reads as hh:mm:ss PM/AM
function formatTime(time) {
var
end_time,
formatted_time,
formatted_end_time,
start_time,
hour = 12,
minute = 10,
second = 10,
meridies;
hour = time.getHours();
if (hour>12) {
hour = hour-12;
meridies = "PM";
} else {
meridies = "AM";
}
minute = time.getMinutes();
if (minute<10) {
minute = "0"+minute;
}
second = time.getSeconds();
if (second<10) {
second = "0"+second;
}
return hour+":"+minute+":"+second+" "+meridies;
}
Here is times.js:
/* global formatTime: true */
/* Please do not remove the comment above. */
// timer to calculate the starting and stopping clicks
var start_time;
var formatted_time;
var end_time;
var formatted_end_time;
var time_change;
$(document).ready(function() {
$("#start").on('click',function() {
$("#start").hide();
$("#stop").show();
$("#time_started").hide();
$("#time_ended").hide();
end_time = new Date();
start_time = new Date();
formatted_time = formatTime(start_time);
});
$("#stop").on('click',function() {
$("#stop").hide();
$("#reset").show();
$("#time_started").hide();
$("#time_ended").show();
end_time = new Date();
formatted_end_time = formatTime(end_time);
$("body").append("<p class='results'>You started at "+formatted_time+".</p>");
$("body").append("<p class='results'>You finished at "+formatted_end_time+".</p>");
time_change = end_time-start_time;
$("body").append("<p class='results'>You counted "+(time_change/1000)+" seconds.</p>");
$("body").append("<p class='results'>You are off by "+(time_change/1000-45)+" seconds.</p>");
});
});
Avoid mixing addClass() / removeClass() vs hide() / show().
It should be obvious what addClass() / removeClass() do. hide() / show() add and remove inline css styles to achieve a similar end result (but inline styles will always take precedence).
$(function() {
$("#reset").on("click", function() {
$(".results").remove();
$("#reset").addClass("hidden");
$("#time_ended").addClass("hidden");
$("#start").removeClass("hidden");
});
// timer to calculate the starting and stopping clicks
var start_time;
var formatted_time;
var end_time;
var formatted_end_time;
var time_change;
$("#start").on("click", function() {
$("#start").addClass("hidden");
$("#stop").removeClass("hidden");
$("#time_started").removeClass("hidden");
$("#time_ended").addClass("hidden");
end_time = new Date();
start_time = new Date();
formatted_time = formatTime(start_time);
});
$("#stop").on("click", function() {
// $("#stop").hide();
$("#stop").addClass("hidden");
// $("#reset").show();
$("#reset").removeClass("hidden");
// $("#time_started").hide();
$("#time_started").addClass("hidden");
// $("#time_ended").show();
$("#time_ended").removeClass("hidden");
end_time = new Date();
formatted_end_time = formatTime(end_time);
$("body").append(
"<p class='results'>You started at " + formatted_time + ".</p>"
);
$("body").append(
"<p class='results'>You finished at " + formatted_end_time + ".</p>"
);
time_change = end_time - start_time;
$("body").append(
"<p class='results'>You counted " + time_change / 1000 + " seconds.</p>"
);
$("body").append(
"<p class='results'>You are off by " +
(time_change / 1000 - 45) +
" seconds.</p>"
);
});
});
function formatTime(time) {
var end_time,
formatted_time,
formatted_end_time,
start_time,
hour = 12,
minute = 10,
second = 10,
meridies;
hour = time.getHours();
if (hour > 12) {
hour = hour - 12;
meridies = "PM";
} else {
meridies = "AM";
}
minute = time.getMinutes();
if (minute < 10) {
minute = "0" + minute;
}
second = time.getSeconds();
if (second < 10) {
second = "0" + second;
}
return hour + ":" + minute + ":" + second + " " + meridies;
}
.hidden {
display: none;
}
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<div id="text">
<p>
Can you internally count 45 seconds precisely?
</p>
</div>
<button id="start">Start Timer</button>
<button id="stop" class="hidden">Stop Timer</button>
<button id="reset" class="hidden">Reset Timer</button>
<span id="time_started" class="hidden">Timer Started</span>
<span id="time_ended" class="hidden">Timer Ended</span>
Also, be careful when appending new content on every round and then just hiding it at the end (instead of actually removing it). You would end up with unnecessarily duplicated html.
Alternatively you could add the .results in the starting html with a class of .hidden to use the same hide/show method for everything.
$(function() {
$("#reset").on("click", function() {
$(".results").addClass("hidden");
$("#reset").addClass("hidden");
$("#time_ended").addClass("hidden");
$("#start").removeClass("hidden");
});
// timer to calculate the starting and stopping clicks
var start_time;
var formatted_time;
var end_time;
var formatted_end_time;
var time_change;
$("#start").on("click", function() {
$("#start").addClass("hidden");
$("#stop").removeClass("hidden");
$("#time_started").removeClass("hidden");
$("#time_ended").addClass("hidden");
end_time = new Date();
start_time = new Date();
formatted_time = formatTime(start_time);
});
$("#stop").on("click", function() {
$("#stop").addClass("hidden");
$("#reset").removeClass("hidden");
$("#time_started").addClass("hidden");
$("#time_ended").removeClass("hidden");
$(".results").removeClass("hidden");
end_time = new Date();
formatted_end_time = formatTime(end_time);
time_change = end_time - start_time;
$('#results-time-started span').text(formatted_time);
$('#results-time-ended span').text(formatted_end_time);
$('#results-time-counted span').text(time_change / 1000);
$('#results-time-off-by span').text(time_change / 1000 - 45);
});
});
function formatTime(time) {
var end_time,
formatted_time,
formatted_end_time,
start_time,
hour = 12,
minute = 10,
second = 10,
meridies;
hour = time.getHours();
if (hour > 12) {
hour = hour - 12;
meridies = "PM";
} else {
meridies = "AM";
}
minute = time.getMinutes();
if (minute < 10) {
minute = "0" + minute;
}
second = time.getSeconds();
if (second < 10) {
second = "0" + second;
}
return hour + ":" + minute + ":" + second + " " + meridies;
}
.hidden {
display: none;
}
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<div id="text">
<p>
Can you internally count 45 seconds precisely?
</p>
</div>
<button id="start">Start Timer</button>
<button id="stop" class="hidden">Stop Timer</button>
<button id="reset" class="hidden">Reset Timer</button>
<span id="time_started" class="hidden">Timer Started</span>
<span id="time_ended" class="hidden">Timer Ended</span>
<p id='results-time-started' class='hidden results'>You started at <span></span>.</p>
<p id='results-time-ended' class='hidden results'>You finised at <span></span>.</p>
<p id='results-time-counted' class='hidden results'>You counted <span></span> seconds.</p>
<p id='results-time-off-by' class='hidden results'>You are off by <span></span> seconds.</p>

12 hour clock not displaying, but 24 hour clock displaying fine

I have this code so that when I click the buttons, it switches between the 12 hours clock and 24 hours clock.
The 24 hour clock displayed, but when I click the 12 hour clock button, nothing happens.
Google Inspect also says nothing. Any help would be appreciated.
function twelvehour() {
var dat = new Date();
var h = dat.getHours()
if (h >= 13) {
var h = dat.getHours() - 12
} else {
var h = dat.getHours()
}
var m = dat.getMinutes()
var s = dat.getSeconds()
if (h >= 12) {
document.getElementById("clock").innerHTML = h + ":" + m + ":" + s + "pm"
} else {
document.getElementById("clock").innerHTML = h + ":" + m + ":" + s
}
}
function tfourhour() {
var dat1 = new Date();
var h1 = dat1.getHours()
var m1 = dat1.getMinutes()
var s1 = dat1.getSeconds()
document.getElementById("clock").innerHTML = h1 + ":" + m1 + ":" + s1
}
setInterval(twelvehour, 1000);
setInterval(tfourhour, 1000);
document.getElementById("twelve").onclick = twelvehour()
document.getElementById("tfour").onclick = tfourhour()
<html>
<head>
<style>
button {
display: inline-block;
}
</style>
<title>Assignment 9c Clock</title>
</head>
<body>
<button type="button" style="width=500, height=500" id="twelve">12 Hour Clock</button>
<button type="button" style="width=500, height=500" id="tfour">24 Hour Clock</button>
<br>
<p id="clock"></p>
<script type="text/javascript" src="sample4.js">
</script>
</body>
</html>
You run two functions at the same time by calling setIterval twice.
twelvehour function doesn't work properly since you set h before it displayed.
Event handlers should be mapped with a function itself not a result of it.
And consider using a function that store the selected function.
let f = twelvehour;
f();
function twelvehour() {
var dat = new Date();
dat.setHours(14); // for test
var h = dat.getHours()
var m = dat.getMinutes()
var s = dat.getSeconds()
if (h >= 12) {
document.getElementById("clock").innerHTML = (h - 12) + ":" + m + ":" + s + "pm"
} else {
document.getElementById("clock").innerHTML = h + ":" + m + ":" + s
}
}
function tfourhour() {
var dat1 = new Date();
dat1.setHours(14); // for test
var h1 = dat1.getHours()
var m1 = dat1.getMinutes()
var s1 = dat1.getSeconds()
document.getElementById("clock").innerHTML = h1 + ":" + m1 + ":" + s1
}
setInterval(() => f(), 1000);
document.getElementById("twelve").onclick = () => { f = twelvehour; f(); }
document.getElementById("tfour").onclick = () => { f = tfourhour; f(); }
<html>
<head>
<style>
button {
display: inline-block;
}
</style>
<title>Assignment 9c Clock</title>
</head>
<body>
<button type="button" style="width=500, height=500" id="twelve">12 Hour Clock</button>
<button type="button" style="width=500, height=500" id="tfour">24 Hour Clock</button>
<br>
<p id="clock"></p>
</script>
</body>
</html>
Your main issue here is assigning onclick in a wrong way. You should drop the parentheses:
document.getElementById("twelve").onclick = twelvehour
Or, put it in the HTML:
<button type="button"
style="width: 500px; height: 500px;"
id="twelve"
onclick="twelvehour()">12 Hour Clock</button>
Here's how I would do it:
function Clock(displayFunc, twelveHour = true, interval = 1000){
let clock;
this.twelveHour = twelveHour; this.interval = interval;
this.start = ()=>{
const fun = ()=>{
let d = new Date, h = d.getHours(), m = d.getMinutes(), s = d.getSeconds(), z = d.getMilliseconds(), p = false;
if(this.twelveHour){
if(h > 12){
h -= 12; p = 'pm';
}
else{
p = 'am';
}
}
else if(h < 10){
h = '0'+h;
}
if(m < 10)m = '0'+m;
if(s < 10)s = '0'+s;
if(z < 10){
z = '00'+z;
}
else if(z < 99){
z = '0'+z;
}
displayFunc({hours:h.toString(), minutes:m.toString(), seconds:s.toString(), am_pm:p});
}
fun(); clock = setInterval(fun, this.interval);
return this;
}
this.stop = ()=>{
clearInterval(clock); clock = undefined;
return this;
}
}
let doc, bod, I; // for use on other loads
addEventListener('load', ()=>{
doc = document; bod = doc.body; I = id=>doc.getElementById(id);
const digital = I('digital'), clock = new Clock(o=>{
digital.textContent = o.hours+':'+o.minutes+':'+o.seconds+' '+o.am_pm;
});
clock.start();
}); // end load
<div id='digital'></div>

How to make HH:MM:SS countdown timer, using javascript?

i've tried to make simple countdown timer, but i don't know how to make something when the timer ends and i don't know how to make timer with hours HH. I can make only minutes MM and second SS.
So, i have this HTML code:
<div class="tadc-time-display">
<span class="tadc-time-display-hours_minutes">00:00</span>
<span class="tadc-time-display-seconds">00</span>
</div>
The JS code i used to have is useless(
You can use Native JavaScript or jQuery, if you want)
function startTimer(duration, display) {
var start = Date.now(),
diff,
minutes,
seconds;
function timer() {
// get the number of seconds that have elapsed since
// startTimer() was called
diff = duration - (((Date.now() - start) / 1000) | 0);
// does the same job as parseInt truncates the float
minutes = (diff / 60) | 0;
seconds = (diff % 60) | 0;
minutes = minutes < 10 ? "0" + minutes : minutes;
seconds = seconds < 10 ? "0" + seconds : seconds;
display.textContent = minutes + ":" + seconds;
if (diff <= 0) {
// add one second so that the count down starts at the full duration
// example 05:00 not 04:59
start = Date.now() + 1000;
}
};
// we don't want to wait a full second before the timer starts
timer();
setInterval(timer, 1000);
}
window.onload = function () {
var fiveMinutes = 60 * 0.1,
display = document.querySelector('#time');
startTimer(fiveMinutes, display);
};
It should also start, stop and reset, but i dont know how to do it( Thanks a lot!
var hours = 0, // obtain these values somewhere else
minutes = 1,
seconds = 20,
target = new Date(),
timerDiv = document.getElementById("timer"),
handler;
function init() {
// set the target date time with the counter values
// counters more then 24h should have a date setup or it wont work
target.setHours(hours);
target.setMinutes(minutes);
target.setSeconds(seconds);
target.setMilliseconds(0); // make sure that miliseconds is 0
timerDiv.innerHTML = target.toTimeString().split(" ")[0]; // print the value
}
function updateTimer() {
var time = target.getTime();
target.setTime(time - 1000); // subtract 1 second with every thick
timerDiv.innerHTML = target.toTimeString().split(" ")[0];
if (
target.getHours() === 0 &&
target.getMinutes() === 0 &&
target.getSeconds() === 0
) { // counter should stop
clearInterval(handler);
}
}
handler = setInterval(updateTimer, 1000);
document.getElementById("stop-button").addEventListener("click", function() {
clearInterval(handler);
});
document.getElementById("start-button").addEventListener("click", function() {
clearInterval(handler);
handler = setInterval(updateTimer, 1000);
});
document.getElementById("reset-button").addEventListener("click", function() {
init();
clearInterval(handler);
});
init();
<div id="timer"></div>
<div>
<button id="start-button">Start</button>
<button id="stop-button">Stop</button>
<button id="reset-button">Reset</button>
</div>
Here is working sample with comments.
try this :
<html lang="en"><head>
<style>
#import "//fonts.googleapis.com/css?family=Bangers";
body {
margin: 0;
}
.wrap {
display: flex;
align-items: center;
justify-content: center;
background:#111;
}
.time-to {
text-align: center;
font-family: Bangers;
color: white;
font-size: 50px;
}
.underline {
text-decoration: underline;
}
.time-to span {
display: block;
font-size: 70px;
}
</style>
<script>
window.console = window.console || function(t) {};
</script>
<script>
if (document.location.search.match(/type=embed/gi)) {
window.parent.postMessage("resize", "*");
}
</script>
</head>
<body translate="no">
<div class="wrap ng-scope" ng-app="app">
<div class="time-to">
prochain event dans :
<span countdown="" date="november 17, 2019 15:15:50" class="ng-isolate-scope underline"></span>
<br>
event : minecraft , ip: 144.76.116.78:40020
</div>
</div>
<script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.3.2/angular.min.js"></script>
<script id="rendered-js">
(function () {
angular.module('app', []).directive('countdown', [
'Util',
'$interval',
function (Util,
$interval) {
return {
restrict: 'A',
scope: {
date: '#' },
link: function (scope,
element) {
var future;
future = new Date(scope.date);
$interval(function () {
var diff;
diff = Math.floor((future.getTime() - new Date().getTime()) / 1000);
return element.text(Util.dhms(diff));
},
1000);
} };
}]).
factory('Util', [
function () {
return {
dhms: function (t) {
var days,
hours,
minutes,
seconds;
if(t < 0) {
t = 0
}
if(t === 0) {
t = 0
}
days = Math.floor(t / 86400);
t -= days * 86400;
hours = Math.floor(t / 3600) % 24;
t -= hours * 3600;
minutes = Math.floor(t / 60) % 60;
t -= minutes * 60;
seconds = t % 60;
if(t < 0) {
t = 0
}
if(t === 0) {
t = 0
}
return [days + 'd',
hours + 'h',
minutes + 'm',
seconds + 's'].join(' ');
} };
}]);
}).call(this);
</script>
</body></html>

How to make javascript timer reload

I have this code of Javascript that i got from a forum for my html page:
<html>
<head>
<title>Countdown</title>
<script type="text/javascript">
// set minutes
var mins = 0.1;
// calculate the seconds (don't change this! unless time progresses at a different speed for you...)
var secs = mins * 60;
function countdown() {
setTimeout('Decrement()',1000);
}
function Decrement() {
if (document.getElementById) {
minutes = document.getElementById("minutes");
seconds = document.getElementById("seconds");
// if less than a minute remaining
if (seconds < 59) {
seconds.value = secs;
} else {
minutes.value = getminutes();
seconds.value = getseconds();
}
secs--;
setTimeout('Decrement()',1000);
}
}
function getminutes() {
// minutes is seconds divided by 60, rounded down
mins = Math.floor(secs / 60);
return mins;
}
function getseconds() {
// take mins remaining (as seconds) away from total seconds remaining
return secs-Math.round(mins *60);
}
</script>
</head>
<body>
<div id="timer">
Minutes:<input id="minutes" type="text" style="width: 14px; border: none; background-color:none; font-size: 16px; font-weight: bold;">:<input id="seconds" type="text" style="width: 26px; border: none; background-color:none; font-size: 16px; font-weight: bold;"> seconds.
</div>
<script>
countdown();
</script>
My question is how can i make it reload when the time is up. so if seconds and minuets = 0, it would reload.
Or if you have a better simple times, please show me how :)
add the following lines in countdown:
if (getseconds() == 0 && getminutes() == 0) {
document.location.reload(true)
}
A more simple (and more beautiful) solution:
<html>
<head>
<title>Countdown</title>
<script type="text/javascript">
// set minutes
var mins = 0.1;
// calculate the seconds (don't change this! unless time progresses at a different speed for you...)
var secs = mins * 60;
function countdown() {
secs = secs - 1;
if (secs < 0) {
document.location.reload(true);
} else {
document.getElementById('countdown').innerHTML = secs;
window.setTimeout('countdown()', 1000);
}
}
window.onload = countdown;
</script>
</head>
<body>
Reloading in <span id="countdown"> </span> seconds.
</body>
</html>

Clock in 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>

Categories