How to change current time with Javascript - javascript

I want to show current time on my webpage. When I push F5, I can get the time, but it's not changing. Help me..
HTML
<div id="time" class="timer">
show_time
</div>
Javascript
var text2 = document.getElementById("time");
var now = new Date();
var hours = now.getHours();
var minutes = now.getMinutes();
var seconds = now.getSeconds();
var dn = "PM";
if (hours<12)
dn="AM";
if (hours>12)
hours=hours-12;
if (hours==0)
hours=12;
if (minutes<=9)
minutes="0"+minutes;
if (seconds<=9)
seconds="0"+seconds;
setInterval(setTime, 1000);
function setTime(){
text2.innerHTML ="현재 시간: <br>"+ hours + ':' +
minutes + ':' + seconds+ "<bn>"+dn;
}
setTime();
Thank you!

Try this
const el = document.getElementById('nav-time');
function updateClock() {
var now = new Date();
var time = now.getHours() + ':' + now.getMinutes() + ':' + now.getSeconds();
el.innerHTML = time;
}
setInterval(updateClock, 1);
<li><span id="nav-time">Clock
<span class="divider"> | </span>

function setTime(){
document.getElementById("time").innerHTML ="현재 시간: <br>"+ hours + ':' +
minutes + ':' + seconds+ "<bn>"+dn;
}
You have to add something to your current code so that your setTime function actually adds its output to the DOM. I used document.getElementById("time") to add the time from your function to the page.

You need to get the current time inside the function, otherwise it will return value that you got when function was called for the firs time
function setTime(){
var text2 = document.getElementById("time");
var now = new Date();
var hours = now.getHours();
var minutes = now.getMinutes();
var seconds = now.getSeconds();
var dn = "PM";
if (hours<12)
dn="AM";
if (hours>12)
hours=hours-12;
if (hours==0)
hours=12;
if (minutes<=9)
minutes="0"+minutes;
if (seconds<=9)
seconds="0"+seconds;
text2.innerHTML ="현재 시간: <br>"+ hours + ':' +
minutes + ':' + seconds+ "<bn>"+dn;
}
setTime();
setInterval(setTime, 1000);
https://jsfiddle.net/1gc8ymkd/

Related

setInterval not updating html element

Basically I'm trying to have my code update the value of an element every second. Problem is my current code only updates it the first time. No errors in console either.
The weird part is that the console.log() keeps running after but the element doesn't update and neither does the time variable
var today = new Date();
var time = today.getHours() + ":" + today.getMinutes() + ":" + today.getSeconds();
var date = today.getFullYear() + '/' + String(today.getMonth() + 1).padStart(2, '0') + '/' + String(today.getDate()).padStart(2, '0');
setInterval(function() {
time = today.getHours() + ":" + today.getMinutes() + ":" + today.getSeconds();
var elTime = document.getElementById("time");
elTime.textContent = time;
console.log(time);
}, 1000);
Try this way, the variables also need to be updated each time the setInterval is executed.
(function() {
setInterval(function() {
var today = new Date();
var time = today.getHours() + ":" + today.getMinutes() + ":" + today.getSeconds();
var date = today.getFullYear() + '/' + String(today.getMonth() + 1).padStart(2, '0') + '/' + String(today.getDate()).padStart(2, '0');
time = today.getHours() + ":" + today.getMinutes() + ":" + today.getSeconds();
var elTime = document.getElementById("time");
elTime.textContent = time;
console.log(time);
}, 1000);
})()
<div id="time"></div>
You need to re-set "Today" for every tick of the interval. Change to this:
setInterval(function(){
var heute= new Date();
time = heute.getHours() + ":" + heute.getMinutes() + ":" + heute.getSeconds();
var elTime = document.getElementById("time");
elTime.textContent = time;
console.log(time);
}, 1000);
A simple working setInterval program looks like the following.
setInterval(() => {
var elTime = document.getElementById("time");
elTime.textContent = parseInt(elTime.textContent) + 1;
}, 1000);
<div id="time">0</div>
Notice all the code that needs execute is inside the scope of the setInterval function. To fix your problem, add all code inside the scope of the function so it runs every single time like so.
setInterval(function() {
//Variables
var today = new Date();
var time = today.getHours() + ":" + today.getMinutes() + ":" + today.getSeconds();
var date = today.getFullYear() + '/' + String(today.getMonth() + 1).padStart(2, '0') + '/' + String(today.getDate()).padStart(2, '0');
time = today.getHours() + ":" + today.getMinutes() + ":" + today.getSeconds();
var elTime = document.getElementById("time");
elTime.textContent = time;
console.log(time);
}, 1000);
<div id="time"></div>
SetInterval is a function call system.
for information: SetInterval can not serve as a precise clock, the durrée between each apple is an indication for the interpreter, and depending on the tasks it must perform elsewhere, it can return beyond the requested period, which is usually the case. For a request of 1000ms, it can realize the call after 1004ms, 1020ms, or even more.
and more easy to use native JS time formating => https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Date/toLocaleTimeString
const elTime = document.getElementById("time")
ShowTime() // first attempt
setInterval(ShowTime, 1000) // next ones
function ShowTime()
{
let t_Now = new Date()
elTime.textContent = t_Now.toLocaleTimeString('default', { hour12:false } )
}
<p id="time"></p>

How do I make my Javascript Clock 'live'?

I would like assistance on making this clock I created in Javascript/HTML update in real-time.
<!DOCTYPE html>
<html>
<head>
<link rel="stylesheet" href="style.css">
<script>
function timer() {
var today = new Date();
var hrs = today.getHours();
var mins = today.getMinutes();
var secs = today.getSeconds();
var mili = today.getMilliseconds();
document.getElementById('txt').innerHTML = "Since midnight, " + hrs + " hours, " + mins + " minutes, " + secs + " seconds, and " + mili + " milliseconds have passed.";
}
</script>
</head>
<body onload="timer()">
<div id="txt"></div>
<body>
<h1>Clock</h1>
</body>
</html>
Any help would be appreciated.
You should create an interval timer and just call your timer function every X milliseconds, as you are displaying millisecond precision you might want to keep this low like 100ms. I suggest using setInterval for this. Just put this in your script block:
setInterval(timer, 100);
Here is a full example:
function timer() {
var today = new Date();
var hrs = today.getHours();
var mins = today.getMinutes();
var secs = today.getSeconds();
var mili = today.getMilliseconds();
document.getElementById('txt').innerHTML = "Since midnight, " + hrs + " hours, " + mins + " minutes, " + secs + " seconds, and " + mili + " milliseconds have passed.";
}
setInterval(timer, 100);
<div id="txt"></div>
Use the setTimeout function (see window.setTimeout)
In your case:
Call the timer function and add
window.setTimeout(timer, 50);
at the very end of the function.
Example:
function timer() {
var today = new Date();
var hrs = today.getHours();
var mins = today.getMinutes();
var secs = today.getSeconds();
var mili = today.getMilliseconds();
document.getElementById('txt').innerHTML = "Since midnight, " + hrs + " hours, " + mins + " minutes, " + secs + " seconds, and " + mili + " milliseconds have passed.";
window.setTimeout(timer, 50);
}
timer();
<div id="txt"></div>

SetInterval Javascript not working- showing blank

I want to create a clock that will update itself every second.
For some reason when I try to run the code I get a blank page.
this is the Javascript part:
function test()
{
var today = new Date();
var day = today.getDate();
var month = today.getMonth();
var year = today.getFullYear();
var hr = today.getHours();
var mins = today.getMinutes();
var sec = today.getSeconds();
document.body.innerHTML = day + "/" + month + "/" + year + " " + hr + ":" + mins + ":" + secs;
}
setInterval(test, 1000);
this is the HTML part:
<html lang="en">
<head>
</head>
<body name="body">
<script type="text/javascript" src="JS-test.js"></script>
</body>
</html>
I've tried a few other variations and none seam to work.
How do I fix it to actually display something?
thanks in advance.
(I am a newbie in javascript)
Change secs to sec
var sec = today.getSeconds();
document.body.innerHTML = day + "/" + month + "/" + year + " " + hr + ":" + mins + ":" + sec;
The script should be written within <script></script>
and secondly, its sec not secs in your last statement of that function.. It works fine.
function test()
{
var today = new Date();
var day = today.getDate();
var month = today.getMonth();
var year = today.getFullYear();
var hr = today.getHours();
var mins = today.getMinutes();
var sec = today.getSeconds();
document.body.innerHTML = day + "/" + month + "/" + year + " " + hr + ":" + mins + ":" + sec;
}
setInterval(test, 1000);
Maybe a little change in your function...
document.onload=setInterval(test,1000);
and do the sec/secs change in your variable declaration

Dynamically update time without refreshing the page

<html>
<head>
<script>
function updateClock() {
var time = now.getHours() + ':' + now.getMinutes(),
document.getElementById('current').innerHTML = time;
setTimeout(updateClock, 1000);
}
</script>
</head>
<body onload="updateClock()">
<p id="current"> </p>
</body>
</html>
Above is the code for dynamically update real time, it is not showing any thing on the browser. Would really appreciate help
Thank you.
Show time using Js :
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('current').innerHTML =
h + ":" + m + ":" + s;
var t = setTimeout(startTime, 500);
}
function checkTime(i) {
if (i < 10) {
i = "0" + i
}; // add zero in front of numbers < 10
return i;
}
<body onload="startTime()">
<p id="current">Time loading..</p>
</body>
OR
Your code edited:
function updateClock() {
var now = new Date();
var time = now.getHours() + ':' + now.getMinutes() + ':' + now.getSeconds();
document.getElementById('current').innerHTML = time;
setTimeout(updateClock, 1000);
}
<body onload="updateClock()">
<p id="current"></p>
</body>
You were missing var now = new Date(); and also now.getSeconds();.
There are some errors in updateClock:
function updateClock() {
var now = new Date()
var time = now.getHours() + ':' + now.getMinutes();
document.getElementById('current').innerHTML = time;
setTimeout(updateClock, 1000);
}
now must be a Date object.
now needed to be a date object
You had a comma instead of a semicolon after now.getMinutes(),
I recommend using
* padding
* setInterval
* window.onload instead of body onload
I added seconds to show it updates. If you only need hours and minutes, change the interval time to 10000 or so.
function pad(num) {
return String("0"+num).slice(-2);
}
function updateClock() {
var now = new Date();
var time = pad(now.getHours()) + ':' + pad(now.getMinutes()) + ":" + pad(now.getSeconds());
document.getElementById('current').innerHTML = time;
}
window.onload = function() {
setInterval(updateClock, 500); // use a shorter interval for better update
}
<p id="current"></p>

Having issue with setInterval

I am having an issue with the setInterval() function in javascript where it will print to my page once and it will not continue to do so. I was wondering if maybe this is a browser issue or something i did wrong.
function printTime() {
var now = new Date();
var hours = now.getHours();
var minutes = now.getMinutes();
var seconds = now.getSeconds();
document.write(hours + ":" + minutes + ":" + seconds + "<br/>");
}
setInterval("printTime()", 1000);
Apart from the poor practice of using "functionName()" instead of just functionName, the code will never work if the interval is beyond the page loading.
document.write will wipe the page after load
Here is a better solution:
<div id="time"></div>
<script>
function pad(str) { return ("0"+str).slice(-2)}
function printTime() {
var now = new Date();
var hours = now.getHours();
var minutes = now.getMinutes();
var seconds = now.getSeconds();
document.getElementById("time").innerHTML+=pad(hours) + ":" + pad(minutes) + ":" + pad(seconds) + "<br/>";
}
setInterval(printTime, 1000);
</script>

Categories