I got this JavaScript Code to display the current time on my website, works perfectly for desktop but it doesn't work on mobile devices
It freezes on the time when the user visits the page
Is it any way to make this possible? Something like refresh the script every sec to show the current time or any other solution?
document.getElementById("clock").innerHTML = GetTime();
function GetTime(){
var d = new Date();
var nhour = d.getHours(),nmin=d.getMinutes();
if (nmin<=9) {
nmin = "0" + nmin
}
return nhour+":"+nmin+"";
}
<span id="clock"></span>
Your help is really appreciated!
EDIT: Thanks to mdickin I realized the clock doesn't update even in desktop. So the entire code has something wrong.
Yes you could use a setInterval, which runs a function at regular intervals (in milliseconds).
function setTime()
{
document.getElementById("clock").innerHTML = GetTime();
}
setInterval(setTime,1000);
You could change the number of milliseconds to suit, depending on how accurate you want to be...but I doubt you would need to worry about being more than a second out either way.
Here's a link with more information about setInterval and setTimeout
Use setInterval to run your GetTime() function every second:
document.getElementById("clock").innerHTML = GetTime();
function GetTime(){
var d = new Date();
var nhour = d.getHours(),nmin=d.getMinutes();
if (nmin<=9) {
nmin = "0" + nmin
}
return nhour+":"+nmin+"";
}
setInterval(GetTime, 1000); // run GetTime every 1000ms
<span id="clock"></span>
Here is a simple program that I wrote in codepen to create a live JS timer. Basically all you need to do is call the function inside a setTimeout function and provide the frequency in milliseconds.
function startTimer() {
var today = new Date();
var hours = today.getHours();
var mins = today.getMinutes();
var sec = today.getSeconds();
mins = checkTime(mins);
sec = checkTime(sec);
document.getElementById('timer').innerHTML =
hours + ":" + mins + ":" + sec;
var t = setTimeout(startTimer, 100);
}
function checkTime(i) {
if (i < 10) {
i = "0" + i
};
return i;
}
<body onLoad="startTimer()">
<div id="timer"></div>
</body>
Here is the link to my codepen
Related
Looking for a Script that will autho refresh page on scheduled local time clock.
Twise a day. Let's say at 8AM and 8PM,
every day, OR
specific week day, cush as Mon-Fri, Mon-Wed, etc.
Notice: recently, found below code and tried this but it doesn't not work. Looking for a proper script based on above description.
setInterval(function(){
var dt = new Date();
var clock_time = dt.getHours() + ":" + dt.getMinutes();
if ( clock_time === '22:10' ) {
location.reload();
}
You have left out the time in setInterval.
You can set 2 times using || (OR) operator.
let interval; // Use clearInterval(interval) to stop the interval
let refreshDelay = 60000; // Every minute
function scheduledReload() {
let dt = new Date();
let time = dt.getHours() + ":" + dt.getMinutes();
if(time ==='08:10' || time === '22:10') {
location.reload();
}
}
interval = setInterval(scheduledReload, refreshDelay);
I have two buttons, show time, and stop time. when click on show time, it set up setTimeout() to update the current time. when stop time is clicked, i want to stop the time 5 sec later. the problem I'm having is that if I click on show time twice, then I click stop time, the time is till ticking. I need to click stop time twice in order to stop the time. so I think there are multiple instances of setTimeout() when i click show time multiple times. I'm wondering how can I make sure there is only one setTimeout(), so even show time is clicked multiple times, it only requires to click on stop time once to stop the time.
<body>
<script>
var iTimeout;
function startTime() {
var today = new Date();
var hour = today.getHours();
var min = today.getMinutes();
var sec = today.getSeconds();
document.getElementById('time').innerHTML =
hour + ":" + min + ":" + sec;
iTimeout = window.setTimeout(startTime, 1000);
}
function stopTimer() {
window.setTimeout(function() {
window.clearTimeout(iTimeout);
console.log("clear");
}, 5000);
}
</script>
</head>
<div id="time"></div>
<button onclick="stopTimer()">stop time</button>
<button onclick="startTime()">show time</button>
</body>
You can clear the iTimeout before starting the new timer in case the user clicks on start time twice
function startTime() {
var today = new Date();
var hour = today.getHours();
var min = today.getMinutes();
var sec = today.getSeconds();
document.getElementById('time').innerHTML =
hour + ":" + min + ":" + sec;
if(iTimeout)
{
window.clearTimeout(iTimeout);
}
iTimeout = window.setTimeout(startTime, 1000);
}
var iTimeout;
function startTime() {
var today = new Date();
var hour = today.getHours();
var min = today.getMinutes();
var sec = today.getSeconds();
document.getElementById('time').innerHTML =
hour + ":" + min + ":" + sec;
// clear the timeout if it exists.
if (iTimeout) {
window.clearTimeout(iTimeout);
}
iTimeout = window.setTimeout(startTime, 1000);
}
function stopTimer() {
window.setTimeout(function() {
window.clearTimeout(iTimeout);
console.log("clear");
}, 5000);
}
<div id="time"></div>
<button onclick="stopTimer()">stop time</button>
<button onclick="startTime()">show time</button>
As #Joyson and #Ayan said, you can check if the iTimeout is already set, and clear it upon every request to create a new timer. i'd do the same, although, if i have to call a function repeatedly after a specific delay, i'd use setInterval instead. makes the code clean.
<script>
var iTimeout;
function getTime() {
var today = new Date();
var hour = today.getHours();
var min = today.getMinutes();
var sec = today.getSeconds();
document.getElementById('time').innerHTML =
hour + ":" + min + ":" + sec;
}
function startTime(){
if(iTimeout)
window.clearInterval(iTimeout);
iTimeout = window.setInterval(getTime, 1000);
}
function stopTimer() {
window.setTimeout(function() {
window.clearInterval(iTimeout);
console.log("clear");
}, 5000);
}
</script>
<div id="time"></div>
<button onclick="stopTimer()">stop time</button>
<button onclick="startTime()">show time</button>
doesn't it?
I have double checked and tested on jshint for syntax errors and such. I have also compared my code to others who created the same clock, but did not see any differences that would cause my clock to crash. I do not understand what is causing this problem.
$(document).ready(function(){
function displayTime() {
var currentTime = new Date();
var hours = currentTime.getHours();
var minutes = currentTime.getMinutes();
var seconds = currentTime.getSeconds();
var miridiem = "AM";
var clockDiv = document.getElementById('clock');
if(seconds < 10) {
seconds = "0" + seconds
}
if(minutes < 10) {
minutes = "0" + minutes
}
if (hours > 12) {
hours = hours - 12
miridiem = "PM"
}
if (hours === 0) {
hours = 12
}
clockDiv.textContent = hours + ":" + minutes + ":" + seconds + " " + miridiem;
setInterval(displayTime, 1000);
}
displayTime();
});
<body>
<div id="clock"></div>
<script src="https://code.jquery.com/jquery-3.0.0.min.js" integrity="sha256-JmvOoLtYsmqlsWxa7mDSLMwa6dZ9rrIdtrrVYRnDRH0=" crossorigin="anonymous"></script>
</body>
Warning: snippet will eat your memory. Don't forget to stop it.
https://jsfiddle.net/9cp9m43h/
You're just misunderstanding the usage of setInterval and setTimeout.
As some commenters mentioned, you could just change your current implementation to use setTimeout and it would function pretty well.
However, in my opinion, the best solution would be to change the way your code works, so that setInterval works correctly:
$(document).ready(function(){
function displayTime() {
var currentTime = new Date();
var hours = currentTime.getHours();
var minutes = currentTime.getMinutes();
var seconds = currentTime.getSeconds();
var miridiem = "AM";
var clockDiv = document.getElementById('clock');
if(seconds < 10) {
seconds = "0" + seconds
}
if(minutes < 10) {
minutes = "0" + minutes
}
if (hours > 12) {
hours = hours - 12
miridiem = "PM"
}
if (hours === 0) {
hours = 12
}
clockDiv.textContent = hours + ":" + minutes + ":" + seconds + " " + miridiem;
}
displayTime();
setInterval(displayTime, 1000);
});
I feel this is better because:
this is what setInterval was designed for: performing the same action over and over at a specific interval.
calling setTimeout manually to reset the timer leaves you open to some clock skew; if it takes a millisecond for your displayTime to run before it sets the timeout, then after 1000 seconds you're probably going to be about 1 second off.
a function called displayTime() sounds like all it's doing is displaying the time--there's nothing to hint that it's also creating a long-term side-effect. The separation of concerns feels better if the timer is set outside of that method.
The effects of displayTime() are easier to test independently when it's not creating asynchronous side-effects.
I think your setInterval() is in the wrong place. You placed it inside the function, which is registering 60 interval monitors per minute so the memory is crashing. If you wanted to trigger the next timeout after the function has been called, you can do that using setTimeout(), within the displayTime() function. But if you do setInterval(), you want that to be called at the same level that your initial displayTime() function is called.
See my fiddle: https://jsfiddle.net/9cp9m43h/3/
every time displayTime() is called it starts a new Interval that calls displayTime() every second.
Therefore every second the function is called twice as often as the time before. After 60 Seconds this is Math.pow(2, 60) //=> 1152921504606847000 times.
Hmm, i'm having a hard time figuring out how it crashed with the setInterval() within the displayTime() function, but working completely fine outside the function.
Because in this case displayTime() is not calling itself not even a roundtrip over setInterval. So it stays a single Interval, and therefore a single function-call every second.
How do I show the current time in the format HH:MM:SS?
You can use native function Date.toLocaleTimeString():
var d = new Date();
var n = d.toLocaleTimeString();
This will display e.g.:
"11:33:01"
MDN: Date toLocaleTimeString
var d = new Date();
var n = d.toLocaleTimeString();
alert("The time is: \n"+n);
function checkTime(i) {
if (i < 10) {
i = "0" + i;
}
return i;
}
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);
document.getElementById('time').innerHTML = h + ":" + m + ":" + s;
t = setTimeout(function() {
startTime()
}, 500);
}
startTime();
<div id="time"></div>
DEMO using javaScript only
Update
Updated Demo
(function () {
function checkTime(i) {
return (i < 10) ? "0" + i : i;
}
function startTime() {
var today = new Date(),
h = checkTime(today.getHours()),
m = checkTime(today.getMinutes()),
s = checkTime(today.getSeconds());
document.getElementById('time').innerHTML = h + ":" + m + ":" + s;
t = setTimeout(function () {
startTime()
}, 500);
}
startTime();
})();
You can do this in Javascript.
var time = new Date();
console.log(time.getHours() + ":" + time.getMinutes() + ":" + time.getSeconds());
At present it returns 15:5:18. Note that if any of the values are less than 10, they will display using only one digit, not two.
Check this in JSFiddle
Updates:
For prefixed 0's try
var time = new Date();
console.log(
("0" + time.getHours()).slice(-2) + ":" +
("0" + time.getMinutes()).slice(-2) + ":" +
("0" + time.getSeconds()).slice(-2));
You can use moment.js to do this.
var now = new moment();
console.log(now.format("HH:mm:ss"));
Outputs:
16:30:03
new Date().toTimeString().slice(0,8)
Note that toLocaleTimeString() might return something like 9:00:00 AM.
Use this way:
var d = new Date();
localtime = d.toLocaleTimeString('en-US', { hour12: false });
Result: 18:56:31
function realtime() {
let time = moment().format('h:mm:ss a');
document.getElementById('time').innerHTML = time;
setInterval(() => {
time = moment().format('h:mm:ss a');
document.getElementById('time').innerHTML = time;
}, 1000)
}
realtime();
<script src="https://cdnjs.cloudflare.com/ajax/libs/moment.js/2.22.1/moment.min.js"></script>
<div id="time"></div>
A very simple way using moment.js and setInterval.
setInterval(() => {
moment().format('h:mm:ss a');
}, 1000)
Sample output
Using setInterval() set to 1000ms or 1 second, the output will refresh every 1 second.
3:25:50 pm
This is how I use this method on one of my side projects.
setInterval(() => {
this.time = this.shared.time;
}, 1000)
Maybe you're wondering if using setInterval() would cause some performance issues.
Is setInterval CPU intensive?
I don't think setInterval is inherently going to cause you significant performance problems. I suspect the reputation may come from an earlier era, when CPUs were less powerful. ... - lonesomeday
No, setInterval is not CPU intensive in and of itself. If you have a lot of intervals running on very short cycles (or a very complex operation running on a moderately long interval), then that can easily become CPU intensive, depending upon exactly what your intervals are doing and how frequently they are doing it. ... - aroth
But in general, using setInterval really like a lot on your site may slow down things. 20 simultaneously running intervals with more or less heavy work will affect the show. And then again.. you really can mess up any part I guess that is not a problem of setInterval. ... - jAndy
new Date().toLocaleTimeString('it-IT')
The it-IT locale happens to pad the hour if needed and omits PM or AM 01:33:01
Compact clock function:
setInterval(function() {
let d = new Date()
console.log(`${d.getHours()}:${d.getMinutes()}:${d.getSeconds()}`)
}, 1000);
This code will output current time in HH:MM:SS format in console, it takes into account GMT timezones.
var currentTime = Date.now()
var GMT = -(new Date()).getTimezoneOffset()/60;
var totalSeconds = Math.floor(currentTime/1000);
seconds = ('0' + totalSeconds % 60).slice(-2);
var totalMinutes = Math.floor(totalSeconds/60);
minutes = ('0' + totalMinutes % 60).slice(-2);
var totalHours = Math.floor(totalMinutes/60);
hours = ('0' + (totalHours+GMT) % 24).slice(-2);
var timeDisplay = hours + ":" + minutes + ":" + seconds;
console.log(timeDisplay);
//Output is: 11:16:55
This is an example of how to set time in a div(only_time) using javascript.
function date_time() {
var date = new Date();
var am_pm = "AM";
var hour = date.getHours();
if(hour>=12){
am_pm = "PM";
}
if (hour == 0) {
hour = 12;
}
if(hour>12){
hour = hour - 12;
}
if(hour<10){
hour = "0"+hour;
}
var minute = date.getMinutes();
if (minute<10){
minute = "0"+minute;
}
var sec = date.getSeconds();
if(sec<10){
sec = "0"+sec;
}
document.getElementById("time").innerHTML = hour+":"+minute+":"+sec+" "+am_pm;
}
setInterval(date_time,500);
<per>
<div class="date" id="time"></div>
</per>
new Date().toLocaleTimeString()
function realtime() {
let time = moment().format('hh:mm:ss.SS a').replace("m", "");
document.getElementById('time').innerHTML = time;
setInterval(() => {
time = moment().format('hh:mm:ss.SS A');
document.getElementById('time').innerHTML = time;
}, 0)
}
realtime();
<script src="https://cdnjs.cloudflare.com/ajax/libs/moment.js/2.22.1/moment.min.js"></script>
<div id="time"></div>
Use
Date.toLocaleTimeString()
// Depending on timezone, your results will vary
const event = new Date('August 19, 1975 23:15:30 GMT+00:00');
console.log(event.toLocaleTimeString('en-US'));
// expected output: 1:15:30 AM
console.log(event.toLocaleTimeString('it-IT'));
// expected output: 01:15:30
console.log(event.toLocaleTimeString('ar-EG'));
// expected output: ١٢:١٥:٣٠
Source
I am in need of virtual time (4 x current date and time). I have managed to display the running clock with the current date and time, but I am unable to the time four times faster than current time.
For example, if the current date is 01-01-2012 00:00:00, the virtual time should
be 01-01-2012 00:00:04
Not only the seconds alone should get multiplied; the corresponding minutes, hours, date, month and year also should get multiplied when seconds crosses 59 virtual seconds. That is, the clock should run live with incremental of four seconds for every second with my date format.
Please see my page: http://www.chemfluence.org.in/sample.html
It's now running with the current time. I want to run this four times faster.
Please see my code below.
<!DOCTYPE html>
<html>
<head>
<script>
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);
document.getElementById('txt').innerHTML =
today.getDate() +
"-" +
(today.getMonth()+1)+"-" +
today.getFullYear() +
" "+h+":"+m+":"+s;
t = setTimeout(function(){startTime()},500);
}
function checkTime(i)
{
if (i<10)
{
i = "0" + i;
}
return i;
}
</script>
</head>
<body onload="startTime()">
<div id="txt"></div>
</body>
</html>
There is a simple formula to determine the virtual time for every given time, knowing the two timestamps and the factor:
var virtualOrigin = Date.parse("2012-01-01T00:00:04"),
realOrigin = Date.parse("2012-01-01T00:00:00"),
factor = 4;
function getVirtual(time) {
return new Date( virtualOrigin + (time - realOrigin) * factor );
}
// usage:
var now = new Date(),
toDisplay = getVirtual(now);
Demo at jsfiddle.net
determine the current time ("START") (as timestamp -- count of seconds since 1970)
when displaying the clock, display (("CURRENT" - "START") * 4) + "START" instead
You can do a setInterval for 1 second and then add 4 seconds to the current date.
(This example just logs the time to the console, but you can easily hook it up to an HTML element.)
var date = new Date();
setInterval(function(){
date = new Date(date.getTime() + 4000);
console.log(date.getHours() + ":" + date.getMinutes() + ":" + date.getSeconds());
}, 1000);