I'm currently learning some Javascript, and I'd made a realtime clock (well actually I modded W3school's code but whatever...I already figured out how to make a clock in PHP so no sense repeating that...)
Butttt the realtime clock doesn't seem to sync up with different devices, and I'd like to know why.
W3schools explains the date object as a count of the milliseconds since 1970, so I can't see why it would be wrong....it looks to me like instead of doing that, it's just mirroring whatever the computer's clock is.
When I pull up the website on a smartphone, the clock is 30 seconds or so off.
Is there maybe some way to make the clock reflect server time instead of each user's computer?
Here is the code
var ampm = "AM"; //Default
var message="";
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);
h=checkTime2(h);
document.getElementById('clocktxt').innerHTML=h+":"+m+":"+s+ " " +ampm + " " + message;
t=setTimeout('startTime()',500);
}
function checkTime(i)
{
if (i<10)
{
i="0" + i;
message = "How long you gonna sit there?";
}
return i;
}
function checkTime2(i)
{
if (i>12)
{
i=i-12;
ampm="PM";
}
return i;
}
window.onload=startTime;
Your code is executed on "client" device - your smartphone, PC whatsoever.
So you have a time set on this device. This 'Date' object actually doesn't know anything about the time on server. The time is determined by the underlying Operating system installed on the client machine.
Your question is not really related to some specific technology (like Java Script, for instance), but rather how to get time synchronized on server and client machine.
Its quite complicated actually.
You can take a step further and ask how you can synchronize time between devices that belong to different time-zones. How about different calculations that should take into consideration 'daylight saving' time period?
As the common answer for time synchronization between computers you can read about Network Time Protocol, NTP
If you have enabled PHP you could do the following:
var serverTimeString = '<?php print date("F d, Y H:i:s", time())?>';
var today = new Date(serverTimeString);
Well, this is how I did it: (Does not vary at all)
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>Clock</title>
</head>
<body>
<div id="MyClockDisplay" class="clock" onload="showTime()">
</div>
<script>
function showTime(){
var date = new Date();
var h = date.getHours(); // 0 - 23
var m = date.getMinutes(); // 0 - 59
var s = date.getSeconds(); // 0 - 59
var session = "PM";
if(h == 02){
h = 12;
}
if(h > 12){
session = "PM";
}
h = (h < 10) ? "0" + h : h;
m = (m < 10) ? "0" + m : m;
s = (s < 10) ? "0" + s : s;
var time = h + ":" + m + ":" + s + " " + session;
document.getElementById("MyClockDisplay").innerText = time;
document.getElementById("MyClockDisplay").textContent = time;
setTimeout(showTime, 1000);
}
showTime();
</script>
<style>
body {
background: url('imagename.jpg');
color: white;
}
.clock {
position: absolute;
top: 50%;
left: 50%;
transform: translateX(-50%) translateY(-50%);
color: #e6967e;
font-size: 60px;
font-family: 'Josefin Sans', sans-serif;
letter-spacing: 7px;
-webkit-transition: 0.5s;
}
.clock:hover {
transform: translateY(-10px);
transition: 0.5s;
font-size: 80px;
color: whitesmoke;
}
</style>
</body>
</html>
It will although differ between countries, but set automatically
The following code will give you the number of seconds from 1970. [Unix timestamp / Epoch time]
Math.round( new Date().getTime() / 1000 )
Related
I have been trying to create an attendance system that prompts a user for check-in and check out. Based on the input given, I have assigned a value time which increments by 1 after 1000 milliseconds(You can check in the code). But it is not working the way it has to. If I give check in and after one hour it doesn't show 1 hour. It is a bit slow than the actual time taken. I am not sure where the fault is. Please help me. For clarifications, I have concatenated the time and time taken after each second which you can see in the page itself. Thanks in advance!
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta http-equiv="X-UA-Compatible" content="IE=edge">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>Document</title>
</head>
<style>
body {
background: black;
color: #fcbe24;
padding: 0 24px;
margin: 0;
display: flex;
flex-direction: column;
justify-content: center;
align-items: center;
font-size: 18px;
font-family: -apple-system, BlinkMacSystemFont, 'Segoe UI', Roboto, Oxygen, Ubuntu, Cantarell, 'Open Sans', 'Helvetica Neue', sans-serif;
}
button {
font-size: 25px;
}
</style>
<body>
<h1 id="header"></h1>
<div>
<button id="start" style="display:block;" onclick="startTimer()">Check-in</button>
<button id="stop" style="display:none;" onclick="stopTimer()">Check-out</button>
</div>
<div id="time"></div>
</body>
<script>
var time = 0;
var startInterval;
function startTimer() {
if (time == 0) document.getElementById("time").innerHTML = "00:00:00";
startInterval = setInterval(startTime, 1000);
document.getElementById('start').style.display = 'none';
document.getElementById('stop').style.display = 'block';
}
function stopTimer() {
clearInterval(startInterval);
document.getElementById('start').style.display = 'block';
document.getElementById('stop').style.display = 'none';
}
function startTime() {
time++;
var seconds = time % 60;
var minutes = Math.floor(time / 60) % 60;
var hours = Math.floor(Math.floor(time / 60) / 60) % 24;
console.log(seconds, minutes, hours);
if (seconds < 10) seconds = "0" + seconds.toString();
else seconds = seconds.toString();
if (minutes < 10) minutes = "0" + minutes.toString();
else minutes = minutes.toString();
if (hours < 10) hours = "0" + hours.toString();
else hours = hours.toString();
var currentdate = new Date();
var datetime = currentdate.getHours() + ":" +
currentdate.getMinutes() + ":" +
currentdate.getSeconds();
document.getElementById("time").innerHTML += "<br>" + datetime + ", " + hours + ":" + minutes + ":" + seconds;
}
</script>
</html>
The current mainstream operating systems are not real-time OSes. They cannot guarantee that, if a program asks them to be notified after X milliseconds, it will be notified after exactly X milliseconds. They guarantee only that the program will be notified and that will not happen before X milliseconds pass.
The programs usually rely on timers provided by the operating system to do their time-related work.
Even if they do not do that, because the multitasking means that a program does not run continuously but it is interrupted by the OS, put to sleep then resumed later, the programs cannot guarantee that a time interval of X milliseconds will take exactly X milliseconds either. More than than, in order to be as close as possible, the programs must rely on the OS timers to be waked up when the time comes.
All in all, no program (on the mainstream operating systems) can guarantee that a time interval of X milliseconds will take exactly X milliseconds; you can rely, however, on the fact that it won't take less than X milliseconds.
In order to achieve your goal regarding time measurement (whatever that goal is), you need to carefully measure the time like this:
Get the current time and store it.
Set a timeout or an interval, as you need.
When the timeout passes and your callback is called, get the current time again.
If the difference between the two times is different than the length of your timeout or interval then adjust the length of the next timeout to compensate, if your processing needs that. Or just remember the difference and adjust it later. This depends entirely on your goal and on the way you implement it (timeout or interval).
If I give check in and after one hour it doesn't show 1 hour.
Adjust/correct it periodically, every time your callback is invoked and it will show 1 hour.
I want to change the quotes every minute.
here is my code. it gets the time and then saves to the ".time" element every second. the js only show the last quote always and sometimes it takes time to show that quote.
the page will reload every second
window.setInterval("reloadpage()", 1000);
function reloadpage() {
let date = new Date();
let ampm;
let hour;
let hours = date.getHours();
//if hours will be more than 12
if (hours <= 12) {
hours = hour;
ampm = "AM";
} else {
hour = hours % 12;
ampm = "PM";
}
let minutes = date.getMinutes();
let seconds = date.getSeconds();
//displaying time
let time = hour + ":" + minutes + ":" + seconds + " " + ampm;
let ctime = document.querySelector(".time");
ctime.innerHTML = time;
}
//reload quotes in every minute
window.setInterval("reloadquote()", 60000);
function reloadquote() {
let quotes = ["hello", "kya hua", "gufufish", "wuwfywoifhw"];
//I think the problem is here
for (i = 0; i <= 3; i++) {
document.getElementById("Quote").innerHTML = quotes[i];
}
}
/*ignore CSS*/
*{
margin:0;
padding:0;
box-sizing: border-box;
}
#Quote{
width:100%;
background:#4cffcf;
padding: 10px 30px 10px;
margin:5px;
font-size:40px;
border-radius:10px;
font-style: italic;
}
<div class="time"></div>
<blockquote id="Quote">Quote Placeholder</blockquote>
Are you always seeing wuwfywoifhw in the quote... If so, then here is what's happening...
Every minute reloadquote will actually be executing, but the problem is when it runs, it executes setting the innerHTML for all the four quotes in the for loop and so remains visible is the last one.
Try this instead...
window.setInterval("reloadquote()", 60 * 1000);
const originalQuotes = ["hello", "kya hua", "gufufish", "wuwfywoifhw"];
let replayedQuotes = originalQuotes;
function reloadquote() {
if (replayedQuotes.length) {
const nextQuote = replayedQuotes[0];
document.getElementById("p1").innerHTML = nextQuote;
replayedQuotes = replayedQuotes.slice(1);
} else {
replayedQuotes = originalQuotes;
reloadQuote();
}
}
This is my countdown javascript code everyday on 23:00 of local time will finish and after 1 hour again will start to countdown for tomorrow and this continues. I wanted to know is it possible to add PHP code to this till after countdown finished everyday It adds "5" to my "Credit" column ("Credit" + 5 ) in my MySQL automatically ? appreciate for any kind of guidance.
<script>
var countDown = (function() {
var startStream;
var endStream;
var streamingText = 'Your match started!';
var updateElement;
// Pad single digit numbers
function pad(n) {
return (n<10?'0':'') + +n;
}
// Format a time difference as hh:mm:ss
// d0 and d1 are date objects, d0 < d1
function timeDiff(d0, d1) {
var diff = d1 - d0;
return pad(diff/3.6e6|0) + ':' + pad((diff%3.6e6)/6e4|0) + ':' + pad(diff%6e4/1000|0);
}
// start, end are UNIX UTC time values in seconds for the start and end of streaming
return function(elementId, start, end) {
var now = new Date();
var returnValue;
// By default, run again just after next full second
var delay = 1020 - now.getMilliseconds();
// turn start and end times into local Date objects
if (start) startStream = new Date(start*1000);
if (end) endStream = new Date(end*1000);
// If now is after endStream, add 1 day,
// Use UTC to avoid daylight saving adjustments
if (now > endStream) {
endStream.setUTCHours(endStream.getUTCHours() + 24);
startStream.setUTCHours(startStream.getUTCHours() + 24);
}
// Store the element to write the text to
if (elementId) updateElement = document.getElementById(elementId);
// If it's streaming time, return streaming text
if (now >= startStream && now < endStream) {
returnValue = streamingText;
// Run again after streaming end time
delay = endStream - now;
} else {
// Otherwise, count down to startStream
returnValue = timeDiff(now, startStream);
}
// Write the time left or streaming text
updateElement.innerHTML = returnValue;
// Call again when appropriate
setTimeout(countDown, delay);
};
}());
// Testing code
// Create dates for a local time of 21:00 today
var myStart = new Date();
myStart.setHours(23,0,0,0);
var myEnd = new Date()
myEnd.setHours(24,0,0,0);
// Create UNIX time values for same time as UTC
var startUTCTimeValue = myStart/1000|0
var endUTCTimeValue = myEnd/1000|0
// Run when page loads
window.onload = function() {
countDown('foo', startUTCTimeValue, endUTCTimeValue);
}
</script>
<font face="Trebuchet MS">
<div id="foo" style="color: white; font-size: 14px; font-weight: bold;"></div>
Jquery Ajax is the way to go here i guess.
It seems like you are very new and might not know what ajax is.
In short with Ajax you can call a webpage url in the background. So You could call www.yourdomain.com/addCredits.php
It will do the same as if you would visit that url in your browser. Just write your SQL Code inside that addCredits.php File and you're done.
Just add something like this to your javascript:
$.ajax({url: "addCredits.php"});
You will have to embed jquery inside your document first though.
<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
And also you might want to wait for that script to load before you call that function:
$( document ).ready(function() {
$.ajax({url: "addCredits.php"});
});
Edit:
Your Counter acutally seems to continue in a loop since it keeps up calling itself in the end.
But i would say just put it where your setTimeout is at the end of your function.
Edit2:
Here is an Example with a Clock, your code seems to be over-complicated to be honest. It doesn't really work when i put it in a fiddle aswell...
You could just use this instead:
function startTime() {
// set time variables h=hour, m=minute, s=second
var today = new Date();
var h = today.getHours();
var m = today.getMinutes();
var s = today.getSeconds();
//check if 0's have to be added for better appearance. no logical use!
m = checkTime(m);
s = checkTime(s);
//display current time on the element with id="txt"
document.getElementById('txt').innerHTML =
h + ":" + m + ":" + s;
//check if its 23:00:00 ... if so call addCredits.php
if(h == 23 && m == 00 && s == 00) {
$.ajax({url: "addCredits.php"});
}
//restart this function every second to update the clock
var t = setTimeout(startTime, 1000);
}
function checkTime(i) {
if (i < 10) {i = "0" + i}; // add zero in front of numbers < 10
return i;
}
<!DOCTYPE html>
<html>
<head>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
</head>
<body onload="startTime()">
<div id="txt"></div>
</body>
</html>
I created a countdown timer in Javascript; it was successful, expect not complete. In fact, mathematically, it is correct, but Google Chrome's browser settings "pause" (for lack of a better term) SetInterval/Timeout, which means that if a user of my countdown program switches between tabs on their browser, then the execution of the function will not occur exactly at the set time limit.
I need help implementing this basic time logic from W3Schools:
http://www.w3schools.com/js/tryit.asp?filename=tryjs_timing_clock
<!DOCTYPE html>
<html>
<head>
<script>
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('txt').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;
}
</script>
</head>
<body onload="startTime()">
<div id="txt"></div>
</body>
</html>
and this attempt to account for the browser SetInterval/Timeout interference: http://jsfiddle.net/7f6DX/31/
var div = $('div');
var a = 0;
var delay = (1000 / 30);
var now, before = new Date();
setInterval(function() {
now = new Date();
var elapsedTime = (now.getTime() - before.getTime());
if(elapsedTime > delay)
//Recover the motion lost while inactive.
a += Math.floor(elapsedTime/delay);
else
a++;
div.css("right", a);
before = new Date();
}, delay);
Thanks for any help that you can provide.
You should use real-world time to update your timer instead of relying on the accuracy of setInterval.
The w3schools example you gave does exactly this; every 500ms it grabs the current time, formats it, and updates the display. When the tab is inactive, this update may occur less frequently than 500ms (Chrome can slow it down to once every 1-2s), but nevertheless, when the update does occur, you will display correct information.
// countdown for 1 minute
countdown(60);
function countdown(seconds) {
// current timestamp.
var now = new Date().getTime();
// target timestamp; we will compute the remaining time
// relative to this date.
var target = new Date(now + seconds * 1000);
// update frequency; note, this is flexible, and when the tab is
// inactive, there are no guarantees that the countdown will update
// at this frequency.
var update = 500;
var int = setInterval(function () {
// current timestamp
var now = new Date();
// remaining time, in seconds
var remaining = (target - now) / 1000;
// if done, alert
if (remaining < 0) {
clearInterval(int);
return;
}
// format
var minutes = ~~(remaining / 60);
var seconds = ~~(remaining % 60);
// display
document.getElementById("countdown").innerHTML
= format(minutes) + ":" + format(seconds);
}, update);
}
function format(num) {
return num < 10 ? "0" + num : num;
}
<div id="countdown"></div>
Run this snippet and switch around to different tabs. Your countdown will be off by a maximum of 500ms (the update frequency).
For what it's worth, a similar idea can be applied to animations.
When designing an animation, you should have a formula for the position x as a function of time t. Your rendering clock (whether it is setInterval, setTimeout, or requestAnimationFrame) is not necessarily reliable, but your physics clock (real-world time) is. You should decouple the two.
Every time you need to render a frame, consult the physics clock for the time t, calculate the position x, and render that position. This is a really great blog post which goes into great detail on animations and physics, from which I borrowed the above idea.
i'm trying to build a page that takes the current hour and minute from the javascript date module and then makes the background color unique based off of that info.
what needs to change to get the html liked with the javascript? (new to this if you cant tell).
HTML
<html>
<head>
<meta charset="UTF-8">
<title>New color for each minute of day</title>
</head>
<body id="body">
<script src="script.js"></script>
</body>
</html>
JAVASCRIPT
var body = document.getElementById("body");
var a = 0;
var b = 0;
var c = 0;
function currentTime() {
var today = new Date();
var hour = today.getHours();
var minute = today.getMinutes();
minute = formatTime(minute);
text.innerHTML = hour + ":" + minute;
return minute
}
function changeColor() {
for (minute =< 59; a + 1);
for (hour =< 24; b + 10);
}
function setScene() {
timeValue = currentTime();
}
window.addEventListener("load", initialScene, false);
document.body.style.backgroundColor= 'rgb(' + a + ',' + b + ',' + c + ')';
Omit the CSS (style tag) in the first example and just use plain JS.
document.getElementsByTagName("body")[0].style.background="rgb("+a+", "+b+", "+c+");";
should do it
That's the main problem. Also, in your changeColor function, you are not using the for loop correctly, although you've got the right idea.
for (minute=0;minute<=59;minute+=1) {
a=minute;
}
for (hour=0;hour=<24;hour+=10) {
b=hour;
}
for loops can be a confusing subject for newcomers to JS, but there are some great tutorials online. Do a Google Search and really take the time to learn what a for loop does sometime, it's a good thing to know.
PS I don't see where c is defined.
I think you ask for a changing background for every minute of the day. You need to define a recurring function that reads the time and changes the color. You have that as setScene.
Now you can call it every 60 seconds automatically by pasting the following somewhere inside initialScene:
setInterval(setScene, 60000);