How should I use setTimeout in this Javascript real-time-clock? - javascript

I was trying to do a real-time-clock but I'm having a problem, the setTimeout isn't working in fact the clock doesn't update itself. May I have your help please?
This is the code that I wrote:
<!DOCTYPE html>
<html>
<head>
<meta charset="utf-8">
<title></title>
</head>
<body>
<p id="p"></p>
<script>
var currentDate = new Date();
function startClock() {
time = currentDate.getHours() + ":" + currentDate.getMinutes() + ":" + currentDate.getSeconds();
document.getElementById("p").innerHTML = time;
setTimeout(startClock, 1000);
}
startClock();
</script>
</body>
</html>

Actually, the setTimeout is working fine, however you instantiate currentDate outside of the function, so it never updates.
This is because the time is only captured when the date is instantiated-- it doesn't update itself. That means if you only instantiate it once, it will only ever hold the time from when it was instantiated.
Try this:
<!DOCTYPE html>
<html>
<head>
<meta charset="utf-8">
<title></title>
</head>
<body>
<p id="p"></p>
<script>
function startClock() {
var currentDate = new Date();
time = currentDate.getHours() + ":" + currentDate.getMinutes() + ":" + currentDate.getSeconds();
document.getElementById("p").innerHTML = time;
setTimeout(startClock, 1000);
}
startClock();
</script>
</body>
</html>

Use setTimeout is correct.
But it is not best solution.
Because it will consume memory exponentially when you call itself.
So, you can use setInterval instead of setTimeout:
<!DOCTYPE html>
<html>
<head>
<meta charset="utf-8">
<title></title>
</head>
<body>
<p id="p"></p>
<script>
function startClock() {
let currentDate = new Date();
time = currentDate.getHours() + ":" + currentDate.getMinutes() + ":" + currentDate.getSeconds();
document.getElementById("p").innerHTML = time;
}
setInterval(startClock, 1000);
</script>
</body>
</html>

Related

How do I add zeros before hours/minute/seconds when they are < 10 in Javascript?

I encountered a problem while trying to create a real-time-clock: I'm trying to show a zero before the number that represents minutes/hours/seconds when they are < 10, but the function doesn't work. May someone explain where I'm wrong and why please? Is it the poisition of the if statement or what? What does i represents?
<!DOCTYPE html>
<html>
<head>
<meta charset="utf-8">
<title></title>
</head>
<body>
<p id="p"></p>
<script>
function startClock() {
var currentDate = new Date();
var time = currentDate.getHours() + ":" + currentDate.getMinutes() + ":" + currentDate.getSeconds();
document.getElementById("p").innerHTML = time;
setTimeout(startClock, 1000);
}
function zeros(i) {
if (i < 10) {
return "0" + i;
} else {
return i;
}
}
startClock();
zeros();
</script>
</body>
</html>
Your zeros function takes a number and add a zero in front if the number is < 10.
You need to call your zeros function when you set the time to convert hours, minutes, and seconds to zero-added form.
<!DOCTYPE html>
<html>
<head>
<meta charset="utf-8">
<title></title>
</head>
<body>
<p id="p"></p>
<script>
function startClock() {
var currentDate = new Date();
var time = zeros(currentDate.getHours()) + ":" + zeros(currentDate.getMinutes()) + ":" + zeros(currentDate.getSeconds());
document.getElementById("p").innerHTML = time;
setTimeout(startClock, 1000);
}
function zeros(i) {
if (i < 10) {
return "0" + i;
} else {
return i;
}
}
startClock();
zeros(); // this doesn't do anything????
</script>
</body>
</html>

Using the time as css background color

Just for fun, I wanted to make my website have a dynamic background color that's an rgb value based on the current time. I did some googling and came up with the following, but it's not working.
index.html
<!DOCTYPE html>
<html>
<head>
<title>Site</title>
<link rel="stylesheet" type="text/css" href="style.css">
<link type="text/javascript" src="date.js">
<style>
p{
font-size: 150%;
}
</style>
</head>
<body>
</body>
</html>
date.js
$(document).ready(function() {
setInterval(function(){currentTime("#idTimeField")}, 500);
});
function currentTime(field) {
var now = new Date();
now = (now.getHours() * 10) + ', ' + (now.getMinutes() * 4) + ', ' + (now.getSeconds() * 4);
$(field).val(now);
}
document.getElementsByName("html").style.backgroundColor = "rgb(" + now + ")";
Can anyone help me with what I'm doing wrong, or an alternate/better way to do this?
I apologize if I did something stupid, I'm quite a javascript noob
Thanks in advance
Here. All jQuery. Code modified to work.
$(document).ready(function() {
setInterval(function(){currentTime("#idTimeField")}, 500);
});
function currentTime(field) {
var now = new Date();
now = (now.getHours() * 10) + ', ' + (now.getMinutes() * 4) + ', ' + (now.getSeconds() * 4);
$(field).val(now);
$('html,body').css({'background-color':'rgb('+now+')'});
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<!DOCTYPE html>
<html>
<head>
<title>Site</title>
<link rel="stylesheet" type="text/css" href="style.css">
<link type="text/javascript" src="date.js">
<style>
p{
font-size: 150%;
}
</style>
</head>
<body>
<div id="idTimeField">20:10:34</div>
</body>
</html>
How about something like this:
$(document).ready(function() {
setInterval(function(){currentTime("#idTimeField")}, 500);
});
function currentTime() {
var now = new Date();
var R = (now.getHours() * 10) ;
var G = (now.getMinutes() * 4) ;
var B = (now.getSeconds() * 4);
document.body.style.backgroundColor = 'rgb(' + [R,G,B].join(',') + ')';
}
Your last line is out of function. And document.getElementByName doesn't work for html tag you should use document.getElementByTagName.
Overal use this instead
$(document).ready(function() {
setInterval(function(){currentTime("#idTimeField")}, 500);
});
function currentTime(field) {
var now = new Date();
now = (now.getHours() * 10) + ', ' + (now.getMinutes() * 4) + ', ' + (now.getSeconds() * 4);
$(field).val(now);
$('body').css('background-color', "rgb(" + now + ")");
}

Why isn't my web page displaying the time (javaScript)

Hey guys in my head I have linked the java script file
<head>
<meta http-equiv="Content-Type" content="text/html; charset=utf-8" />
<title>Tech News</title>
<link href="layout.css" rel="stylesheet" type="text/css" />
<script type ="text/javascript" src=" script.ja"> </script>
and in the java script file I have this code
window.onload = initDate;
function initDate()
{
now = new Date();
localtime = now.toString();
globaltime = now.toGMTString();
document.write("<b> Local time: </b> " + localtime + "<br>");
hours = now.getHours();
mins = now.getMinutes();
secs = now.getSeconds();
document.write ("<font size = '+1'>");
document.write(hours + ":" + mins +":" + secs);
document.write("</font>");
document.getElementById("time").innerHTML = dtString;
}
Now this code should display the string in thie div tag but it doesn't
document.getElementById("time").innerHTML = dtString;
Here is the div tag.
<div id="time"> <!--Time-->
</div>
My website is 100& verified with no coding errors, both HTML and CSS.
So what will be the problem?
Thanks to Patrick I realized that I did not declare dtString.
Instead of complicating things the simple solution was to copy the text in to a div tag, which I had found useful since it displayed the date and time.
<div id="date">
<script>
now = new Date();
localtime = now.toString();
globaltime = now.toGMTString();
document.write(localtime);
hours = now.getHours();
mins = now.getMinutes();
secs = now.getSeconds();
document.write ("<font size = '+1'>");
document.write(hours + ":" + mins +":" + secs);
document.write("</font>");
</script>
</div>

when implementing javascript countdown the other html elements disappear

I made a layout and had everything set and when I implement the counter portion under my text all the other HTML elements disappear why is that? Also is there any way I can make an email alert when the counter gets to a specific time?
<!doctype html>
<html lang="en">
<head>
<script type="text/javascript" src="http://ajax.googleapis.com/ajax/libs/jquery/1.4.4/jquery.min.js"></script>
<meta charset="utf-8" />
<meta name="viewport" content="initial-scale=1.0, maximum-scale=1.0, user-
scalable=0, width=device-width;">
<title>Welcome to Tiffany & Co.</title>
<link rel="stylesheet" href="index.css"
type="text/css" media="screen" />
<script src="http://code.jquery.com/jquery-1.7.2.min.js"></script>
<!--Enable media queries in some unsupported subrowsers-->
<script type="text/javascript" src="css3-mediaqueries.js"></script>
<script type="text/javascript" src="main.js"></script>
</head>
<body>
<div id="wrapper">
<h1>Welcome to Store</h1>
<p>The WiFi Password is:</p>
<h2 align=center>
<font color="red">Diamonds</font>
</h2>
<p>It will change in:</p>
<p>
<script type="text/JavaScript">
window.document.onload = function () {
tick();
setInterval(tick, 1000);
};
function tick() {
var d = new Date();
var currentDate = new Date(d.getUTCFullYear(),
d.getUTCMonth(), d.getUTCDate(), d.getUTCHours(),
d.getUTCMinutes(), d.getUTCSeconds(),
d.getUTCMilliseconds());
var endDate = new Date(currentDate.getFullYear(),
currentDate.getMonth(), currentDate.getDate() + (30
/*
saturday */
- currentDate.getDay()), 16
/* 9 AM Mountain
Time = 4 PM GMT */
);
var secondsUntilSaturday = Math.floor((endDate.getTime() - currentDate.getTime()) / 1000);
var timeUntilSaturday = secondsToTime(secondsUntilSaturday);
document.body.innerHTML = (timeUntilSaturday.h + " hours, " + timeUntilSaturday.m + " minutes, " + timeUntilSaturday.s + "
seconds");
}
function secondsToTime(secs) {
var hours = Math.floor(secs / (60 * 60));
var divisor_for_minutes = secs % (60 * 60);
var minutes = Math.floor(divisor_for_minutes / 60);
var divisor_for_seconds = divisor_for_minutes % 60;
var seconds = Math.ceil(divisor_for_seconds);
var obj = {
"h": hours,
"m": minutes,
"s": seconds
};
return obj;
}
</script>
<div id="logo">
<img src="logo.png" width="108" height="14" alt="Tiffany & Co." />
</div>
</div>
</body>
</html>
Your HTML content disappears because of the line:
document.body.innerHTML = (timeUntilSaturday.h + " hours, " + timeUntilSaturday.m + " minutes, " + timeUntilSaturday.s + " seconds");
document.body.innerHTML will write content to the body element, replacing anything that's there. You can replace document.body.innerHTML with document.write.
To answer your second question, no JavaScript can't send email on it's own, but via AJAX it can call a script on your server to send email.
That's because you're replacing whole body content with your timer
document.body.innerHTML = (
timeUntilSaturday.h +" hours, "+
timeUntilSaturday.m +" minutes, "+ timeUntilSaturday.s +"
seconds"
);
Instead of this add <div> for timer and set content with your timer
<div id="timer"></div>
<script>
document.getElementById('timer').innerHTML = (
timeUntilSaturday.h +" hours, "+
timeUntilSaturday.m +" minutes, "+ timeUntilSaturday.s +"
seconds"
);
</script>
Since you're refrencing JQuery, I've used that for you, but really only in one spot...
This should do what you need it to do: Here's a fiddle
Also here's the code from that fiddle:
<script>
//start your interval to update your timer.
setInterval(function() {
//get ms until Saturday 9AM.
var ms = untilTimeOfWeek(6, 9, 0, 0);
$('#timer').text(getHours(ms) + ' hours ' + getMinutes(ms) + ' minutes ' + getSeconds(ms) + ' seconds');
}, 100);
//gets the time left until a specific time of week.
function untilTimeOfWeek(day, hour, min, sec) {
var currdate = new Date();
var currday = currdate.getDay();
var daydiff = (day - currdate.getDay()) * 86400000;
var hourdiff = (hour - currdate.getHours()) * 3600000;
var mindiff = (min - currdate.getMinutes()) * 60000;
var secdiff = (sec - currdate.getSeconds()) * 1000;
return daydiff + hourdiff + mindiff + secdiff;
}
//get the hours from some milliseconds.
function getHours(ms) {
return Math.floor(ms / 3600000);
}
//get the minutes from some milliseconds.
function getMinutes(ms) {
return Math.floor((ms % 3600000) / 60000);
}
//get the seconds from some milliseconds.
function getSeconds(ms) {
return Math.floor(((ms % 3600000) % 60000) / 1000);
};​
</script>
<div id="timer"></div>
NOTE: +new Date is just shorthand for converting a Date to a numeric type in JavaScript.
I hope that helps.
EDIT: Updated to get 9am the following Saturday.

How to display system time?

I want to display the system time on my jsp page. How can i do it? I'm trying this but only date is getting displayed that and not the time. It's all working fine in Internet Explorer but not in other browsers.
<td colspan="1" height="4" align="left" width="260" >
<font class="welcome1">
<strong>
<script language="JavaScript" src="js/date.js"></script>
<span id="clock">
<script language="JavaScript"
src="js/digitalClock.js"></script>
</span>
</strong>
</font>
</td>
Displaying the time on a web-page using js should be trivial .
new Date().toLocaleString() // displays date and time
new Date().toLocaleDateString() // displays date
new Date().toLocaleTimeString() // displays time
To display time you can use Date.
<html>
<head>
<script type="text/javascript">
<!--
function updateTime() {
var currentTime = new Date();
var hours = currentTime.getHours();
var minutes = currentTime.getMinutes();
var seconds = currentTime.getSeconds();
if (minutes < 10){
minutes = "0" + minutes;
}
if (seconds < 10){
seconds = "0" + seconds;
}
var v = hours + ":" + minutes + ":" + seconds + " ";
if(hours > 11){
v+="PM";
} else {
v+="AM"
}
setTimeout("updateTime()",1000);
document.getElementById('time').innerHTML=v;
}
updateTime();
//-->
</script>
</head>
<body>
<h4>Current Time: <span id="time" /></h4>
</body>
</html>
I've tested it in firefox and chrome. Found on this site.
Edit: time now gets updated every second.
You should read the documentation about the Date object in JavaScript (Date). It would be easier if you post the JS source.
/* set Date */
function tick() {
/* Get date in epoch */
var epoch = Date.now();
document.querySelector("#epoch").innerHTML = epoch;
/* Separate epoch */
var datetime = new Date(epoch);
var year = datetime.getFullYear();
var month = datetime.getMonth() + 1; // (0-11)
var date = datetime.getDate();
var hour = datetime.getHours();
var minute = datetime.getMinutes();
var second = datetime.getSeconds();
document.querySelector("#datetime").innerHTML =
year + "-" + addZero(month) + "-" + addZero(date) + " " +
addZero(hour) + ":" + addZero(minute) + ":" + addZero(second);
}
// Add 0 if argument < 10
function addZero(i) {
if (i < 10) {
i = "0" + i
};
return i;
}
/* Call tick in interval 1 second */
setInterval(tick, 1000);
<p id="epoch"></p>
<p id="datetime"></p>
This seems the easiest solution, which uses setInterval with two arguments, the first being a callback, the second the interval in ms:
setInterval(function(){
document.write(new Date().toLocaleTimeString();
},1000);
So my solution should be the accepted answer because it is a real time.
For Date You can use below Javascript. Time will display in a text box. You can modify as per your requirement.
<html>
<head>
<script type="text/javascript">
var timer = null
function stop()
{
clearTimeout(timer)
}
function start()
{
var time = new Date()
var hours = time.getHours()
var minutes = time.getMinutes()
var seconds = time.getSeconds()
var clock = hours + ":" + minutes + ":" + seconds
document.forms[0].display.value = clock
timer = setTimeout("start()",1000)
}
</script>
</head>
<body onload="start()" onunload="stop()">
<form>
<input type="text" name="display" size="20">
</form>
</body>
</html>

Categories

Resources