How can I make this clock working without refreshing website? - javascript

I have problem with this clock. At first timer didn't show up so I used defer and it appeared but time is only changing when I refresh website.
I just want to make this timer change itself with the real world time not only when I refresh website.
const hourEl = document.getElementById('hour')
const minEl = document.getElementById('minutes')
const secEl = document.getElementById('seconds')
const ampmEl = document.getElementById('ampm')
function clockUpdate() {
let h = new Date().getHours()
let m = new Date().getMinutes()
let s = new Date().getSeconds()
let ampm = 'AM'
if (h > 12) {
h = h - 12;
ampm = 'PM';
}
hourEl.innerHTML = h;
minEl.innerHTML = m;
secEl.innerHTML = s;
}
clockUpdate();
<span id="hour"></span>:<span id="minutes"></span>:<span id="seconds">:/span> <span id="ampm"></span>

You can use setTimeout(functionRef, delay) for repeat a function after a number of milliseconds and put your function each seconds.

Put your code inside setInterval
const hourEl = document.getElementById('hour')
const minEl = document.getElementById('minutes')
const secEl = document.getElementById('seconds')
const ampmEl = document.getElementById('ampm')
function clockUpdate() {
let h = new Date().getHours()
let m = new Date().getMinutes()
let s = new Date().getSeconds()
let ampm = 'AM'
if (h > 12) {
h = h - 12;
ampm = 'PM';
}
hourEl.innerHTML = h;
minEl.innerHTML = m;
secEl.innerHTML = s;
}
const int = setInterval(clockUpdate, 1000);
<span id="hour"></span>
<span id="minutes"></span>
<span id="seconds"></span>
<span id="ampm"></span>

Just wrap in a setInterval - here I use half a sec since setInterval is not super reliable
I also use textContent and pad the numbers.
You forgot the ampm too
const hourEl = document.getElementById('hour')
const minEl = document.getElementById('minutes')
const secEl = document.getElementById('seconds')
const ampmEl = document.getElementById('ampm')
function clockUpdate() {
let h = new Date().getHours()
let m = new Date().getMinutes()
let s = new Date().getSeconds()
let ampm = 'AM'
if (h > 12) {
h = h - 12;
ampm = 'PM';
}
hourEl.textContent = String(h).padStart(2,"0");
minEl.textContent = String(m).padStart(2,"0");
secEl.textContent = String(s).padStart(2,"0");
ampmEl.textContent= ampm;
}
setInterval(clockUpdate,500);
<span id="hour"></span>:<span id="minutes"></span>:<span id="seconds"></span>:<span id="ampm"></span>

You call the clockUpdate() function only once. Consider moving it into a setInterval()-function that runs every second (or faster for better accuracy)... like so:
setInterval(clockUpdate, 1000);

Related

Showing complete 24hr time display (00:00:00)

I have a basic script to display PST time based on 24:00hr UTC clock. Everything is working fine except it only displays 0:00:00 (h:m:s) for hours 0-9am and I want to have an extra 0 as a prefix (ex: 00:00:00).
My script is:
function startTime() {
const today = new Date();
let h = today.getUTCHours()-8;
let m = today.getUTCMinutes();
let s = today.getUTCSeconds();
m = checkTime(m);
s = checkTime(s);
document.getElementById('txt').innerHTML = h + ":" + m + ":" + s;
setTimeout(startTime, 1000);
}
I tried adding the following with no such luck:
function checkTime(h) {
if (h < 10) {h = "0" + h}; // add zero in front of numbers < 10
return h;
}
Note that the en-GB locale displays half-past midnight as 00:30:00, but the en-US locale displays it as 24:30:00.
const today = new Date();
const time = today.toLocaleTimeString('en-GB',
{timeZone: 'America/Los_Angeles', hour12: false})
console.log(time)
Maybe you forgot to call h = checkTime(h);
function startTime() {
const today = new Date();
let h = today.getUTCHours()-8;
let m = today.getUTCMinutes();
let s = today.getUTCSeconds();
h = checkTime(h);
m = checkTime(m);
s = checkTime(s);
document.getElementById('txt').innerHTML = h + ":" + m + ":" + s;
setTimeout(startTime, 1000);
}
function checkTime(h) {
if (h < 10) {h = "0" + h}; // add zero in front of numbers < 10
return h;
}
startTime();
<div id="txt"></div>

Clock not working I need help, it's not working

I followed a tutorial on YT on how to put a clock, I've copied the exact code (well not exactly because of the "id") mine seems to be not working. this is my code
const hourEl = document.getElementsById ("hour");
const minuteEl = document.getElementById("minutes");
const secondsEl = document.getElementById("seconds");
const ampmEl = document.getElementById("ampm");
function updateClock (){
let h = new Date().getHours();
let m = new Date().getMinutes();
let s = new Date().getSeconds();
let ampm = "AM";
if(h> 12) {
h = h - 12;
ampm= "PM";
}
h = h > 10 ? "0" + h: h;
m = m > 10 ? "0" + m: m;
s = s > 10 ? "0" + s: s;
hourEl.innerText = h;
minuteEl.innerText = m;
secondsEl.innerText = s;
ampmEl, (innerText= ampm);
setTimeout(()=>{
}, 1000)
}
updateClock();
Mostly you just need to call the function from your timeout, but then you need to flip your > to < in your comparison, and fix a few typos (document.getElementsById, for example, should be document.getElementById):
const hourEl = document.getElementById ("hour");
const minuteEl = document.getElementById("minutes");
const secondsEl = document.getElementById("seconds");
const ampmEl = document.getElementById("ampm");
function updateClock (){
let h = new Date().getHours();
let m = new Date().getMinutes();
let s = new Date().getSeconds();
let ampm = "AM";
if(h> 12) {
h = h - 12;
ampm= "PM";
}
h = h < 10 ? "0" + h: h;
m = m < 10 ? "0" + m: m;
s = s < 10 ? "0" + s: s;
hourEl.innerText = h;
minuteEl.innerText = m;
secondsEl.innerText = s;
ampmEl, (innerText= ampm);
setTimeout(()=>{
updateClock()
}, 1000)
}
updateClock();
div {
display: inline-block;
}
<div id="hour"></div>:
<div id="minutes"></div>:
<div id="seconds"></div>
<div id="ampm"></div>

I have a function with many variables. How do I use them in another function?

var min = document.getElementById("minutes");
var sec = document.getElementById("second");
//sets a time interval to repeat.
setInterval(() => { //function() is the same as () => {} or () =>
let d = new Date(); //creating a variable to get the Time
let h = d.getHours(); //creating a variable to get hours and so on..
let m = d.getMinutes();
let s = d.getSeconds();
var Hours = 30*h+m/2+s/120;//calculating
var Minutes = 6*m+s/10;
var Seconds = 6*s;
hou.style.transform = `rotate(${Hours}deg)`;
min.style.transform = `rotate(${Minutes}deg)`;
sec.style.transform = `rotate(${Seconds}deg)`;
},1000)
function setAlarm(){
let h = document.getElementById("h");
let m = document.getElementById("m");
let s = document.getElementById("s");
if (h.innerHTML==Hours){
console.log(true);
}
}
I want to print true in my console if the value of the variable h in setAlarm() function is equal to the Hours variable in setInterval().
How do I do that?
I'm not positive this is what your'e asking but I'm pretty sure all you need to do is move the variable declarations out of the function like.
var min = document.getElementById("minutes");
var sec = document.getElementById("second");
let Hours;
//sets a time interval to repeat.
setInterval(() => { //function() is the same as () => {} or () =>
let d = new Date(); //creating a variable to get the Time
let h = d.getHours(); //creating a variable to get hours and so on..
let m = d.getMinutes();
let s = d.getSeconds();
Hours = 30*h+m/2+s/120;//calculating
var Minutes = 6*m+s/10;
var Seconds = 6*s;
hou.style.transform = `rotate(${Hours}deg)`;
min.style.transform = `rotate(${Minutes}deg)`;
sec.style.transform = `rotate(${Seconds}deg)`;
},1000)
function setAlarm(){
let h = document.getElementById("h");
let m = document.getElementById("m");
let s = document.getElementById("s");
if (h=Hours){
console.log(true);
}
}
Edit
As stated in the comments there are some issues with the code, here is my advice to you. Don't use duplicate identifier names in different functions as it will probably confuse you as a begginer. Move all variable names that need accessed from multiple functions to the global scope.
Just nope, but you can either expose the variable to upper scope or just invoke the setAlarm function in setInterval.
var min = document.getElementById("minutes");
var sec = document.getElementById("second");
//sets a time interval to repeat.
setInterval(() => { //function() is the same as () => {} or () =>
let d = new Date(); //creating a variable to get the Time
let h = d.getHours(); //creating a variable to get hours and so on..
let m = d.getMinutes();
let s = d.getSeconds();
var Hours = 30*h+m/2+s/120;//calculating
var Minutes = 6*m+s/10;
var Seconds = 6*s;
hou.style.transform = `rotate(${Hours}deg)`;
min.style.transform = `rotate(${Minutes}deg)`;
sec.style.transform = `rotate(${Seconds}deg)`;
setAlarm(Hours);
},1000)
function setAlarm(Hours){
let h = document.getElementById("h");
let m = document.getElementById("m");
let s = document.getElementById("s");
if (h == Hours){
console.log(true);
}
}

Countdown Timer Ends Meessage

A few days ago, I created countdown timer by watching a video on YouTube. The countdown timer is completely perfect but one thing is missing from it. When the timer goes to the zero it will hide from the page.
I want to show some text when timer ends. Like if timer goes to zero then timer hides and show this message "You are too late. Stay with us".
This is a .js code in which I need some modification.
const dayDisplay = document.querySelector(".days .number");
const hourDisplay = document.querySelector(".hours .number");
const minuteDisplay = document.querySelector(".minutes .number");
const secondDisplay = document.querySelector(".seconds .number");
const countdownContainer = document.querySelector(".countdown-container");
const endDate = new Date("August 04 2020 10:38:00");
let saleEnded = false;
const updateTimer = () => {
if(countdownContainer) {
let currentDate = new Date();
let difference = endDate.getTime() - currentDate.getTime();
if (difference <= 1000) {
saleEnded = true;
}
const second = 1000;
const minute = second * 60;
const hour = minute * 60;
const day = hour * 24;
let newDay = Math.floor(difference / day);
let newHour = Math.floor((difference % day) / hour);
let newMiute = Math.floor((difference % hour) / minute);
let newSecond = Math.floor((difference % minute) / second);
dayDisplay.innerText = newDay < 10 ? "0" + newDay : newDay;
hourDisplay.innerText = newHour < 10 ? "0" + newHour : newHour;
minuteDisplay.innerText = newMiute < 10 ? "0" + newMiute : newMiute;
secondDisplay.innerText = newSecond < 10 ? "0" + newSecond : newSecond;
};
};
setInterval(() => {
if (!saleEnded) {
updateTimer();
} else {
countdownContainer.style.display = "block";
}
}, 1000);
Try this?
setInterval(() => {
if (!saleEnded) {
updateTimer();
} else {
countdownContainer.style.display = "block";
countdownContainer.innetHTML="You are too late. Stay with us";
}
}, 1000);

SetInterval() within setInterval() at different times

I would like to ask how is it possible to run a function every 60 seconds which has another timer inside it that only runs every 5 minutes
function systemTime() {
let currentTime = new Date();
let diem = "AM";
let h = currentTime.getHours();
let m = currentTime.getMinutes();
let s = currentTime.getSeconds();
if (h == 0) h = 12;
if (h > 12) diem = "PM";
if (h < 10) h = "0" + h;
if (m < 10) m = "0" + m;
if (s < 10) s = "0" + s;
return {
h: h.toString(),
m: m.toString(),
diem: diem
}
}
async function serverTime() {
let timeUrl = 'https://worldtimeapi.org/api/timezone/Europe';
let response = await fetch(timeUrl);
let data = await response.json();
let timestamp = data.datetime;
let time = timestamp.split('T')[1].split('.')[0];
let timeArray = time.split(':');
if(parseInt(timeArray[0]) > 12) timeArray[2] = 'PM'
else timeArray[2] = 'AM';
return {
h: timeArray[0],
m: timeArray[1],
diem: timeArray[2]
}
}
async function clock() {
let h, m, diem;
let container = document.querySelector('#displayClock');
container.innerHTML = `${h} : ${m}`;
setInterval(() => clock(), 60000);
// I would like to grab the server time every 5 min for comparison
setInterval(() => {}, 60000*5) // set minutes and hours to the server time
}
I would like to call the clock() function every 60s to display the time on a page but at the same time I would like to call the serverTime() function every 5 minutes to compare the values and take the serverTime if they are not the same.
Calling clock() every 60s isn't the problem. setInterval will solve this but if within it I set an Interval of 5 min then every 10 seconds there will be a new 5 min interval set?
Thankyou very much for your help.
You are recursively setting intervals:
async function clock() {
//...
setInterval(() => clock(), 60000);
setInterval(() => {}, 60000*5);
}
So every time you call clock (every minute), you are setting more and more intervals for both clock and, well, an empty function. (It looks like you forgot to try to call serverTime?)
If you want to call clock every 60 seconds, then just set an interval to call it every 60 seconds:
async function clock() {
//...
}
setInterval(clock, 60000);
If you want to call serverTime every 5 minutes, then just set an interval to call it every 5 minutes:
async function serverTime() {
//...
}
setInterval(serverTime, 300000);
There's no need to do this recursively. Doing so means that setting an interval is part of the operation being repeated, which isn't what you want.
Edit: To demonstrate the problem, watch your browser console on this link: https://jsfiddle.net/Laqt4oe5 How many times do you expect the number to increase every 3 seconds? How many times is it actually increasing?
I have used this to solve the issue and obtain what i wanted
/**
* Display a digital clock
*
* #param {string} container - placement of the clock on the page
*/
function systemTime() {
let currentTime = new Date();
let diem = "AM";
let h = currentTime.getHours();
let m = currentTime.getMinutes();
let s = currentTime.getSeconds();
if (h == 0) h = 12;
if (h > 12) diem = "PM";
if (h < 10) h = "0" + h;
if (m < 10) m = "0" + m;
if (s < 10) s = "0" + s;
return {
h: h.toString(),
m: m.toString(),
diem: diem
}
}
/**
* Returns an object containing hours and minutes from the worldTimeAPI
*/
async function serverTime() {
let timeUrl = 'https://worldtimeapi.org/api/timezone/Europe/Berlin';
let response = await fetch(timeUrl);
let data = await response.json();
let timestamp = data.datetime;
let time = timestamp.split('T')[1].split('.')[0];
let timeArray = time.split(':');
if(parseInt(timeArray[0]) > 12) timeArray[2] = 'PM'
else timeArray[2] = 'AM';
console.log('Time fetched from world API');
return {
h: timeArray[0],
m: timeArray[1],
diem: timeArray[2]
}
}
/**
* Fires every 5 min and compares server and system times
*/
async function compareTime() {
let server = await serverTime();
let system = systemTime();
let container = document.querySelector('#displayClock');
if(system.h != server.h || system.m != server.m) container.innerHTML = `${server.h} : ${server.m} ${server.diem}`;
else container.innerHTML = `${system.h} : ${system.m} ${system.diem}`;
setInterval(() => compareTime(), 60000);
}
/**
* Fires every 1 min and displays system time
*/
function displayTime() {
let system = systemTime();
let h = system.h;
let m = system.m;
let diem = system.diem;
let container = document.querySelector('#displayClock');
container.innerHTML = `${h} : ${m} ${diem}`;
setInterval(() => displayTime(), 60000);
}

Categories