Javascript timer won't countdown to set time - javascript

I'm having an issue with a timer i'm working on, what should happen is that the counter should countdown to a specific time which is defined by me. However for some reason the time i have defined is just ignored and it counts down to the next hour. What i am essentially trying to do is set a timer that will count down the time left to a number of specific times, so far i cannot even get it to work for one single defined time. I've attached a JsFiddle which contains all relevant code. Also would it possible to store the times in an array and have the timer count down to each defined time? Thanks in advance!
var definedTime = new Date('Jan 31, 2015 05:00'); // military time to countdown TO
function ShowTimes() {
var now = new Date();
var hrs = definedTime.getHours() - now.getHours() - 1;
if (hrs < 0) {
hrs += 24;
}
var mins = 59 - now.getMinutes();
var secs = 59 - now.getSeconds();
var str = '';
str = now.toString();
str += '<br>Time until 05:00';
str += '<br>'+hrs+' hours ' + mins + ' minutes ' + secs + ' seconds';
document.getElementById('timer').innerHTML = str;
}
var _cntDown;
function StopTimes() {
clearInterval(_cntDown);
}
<body onload="_cntDown=setInterval('ShowTimes()',1000)">
<div id="timer"></div>
<button onclick="StopTimes()">Stop</button>
</body>

Related

Timer not working when using readline-sync (Javascript)

I am making a game that keeps track of the time you take to complete the game, however i realised that the timer does not continue when i am asking for input.I tried to wait 10 seconds before typing a input but after i input a value the time is 00:00.Must i create a separate file for the timer or is there a possible way for the timer to run.Please help thanks!
var readline = require('readline-sync');
seconds = 0;
minute = 0;
timer = setInterval(() => {
if (seconds == 60) {
seconds = 0;
minute++;
}
seconds++;
}, 1000);
var input = readline.question('Input:');
clearInterval(timer);
//String to show time
if (minute < 10 && seconds < 10)
time = '0' + minute + ':0' + seconds;
else if (minute < 10 && seconds >= 10)
time = '0' + minute + ':' + seconds;
else if (minute >= 10 && seconds < 10)
time = minute + ':0' + seconds;
else
time = minute + ':' + seconds;
console.log(time);
It is easier just to create a Date object with new Date() and substract it from another Date created after the user Input.
var dateStart = new Date();
var input = readline.question('Input:');
var difference = new Date() - dateStart(); // time elapsed in milliseconds
For more complex cases I'd recommend looking up the libraries moment.js or date-fns.

My JavaScript clock widget crashes Firefox

I am a JavaScript noob and realise that I need assistance.
All I want is to show a simple real-time clock with the time and AM/PM in separate SPANs.
The issue is that if I keep the tab open for 20-40 minutes (varies depending on how many other tabs I have open), it crashes the tab with an out of memory error. I have only tested this on Firefox (72.0.2) for now.
Why is my code so awfully memory intensive? It usually starts at around 2.4MB and then gradually increases and exceeds 42MB, then drops again, increases again and repeats the cycle several times until the tab crashes.
I've read aboout Garbage Collection but have no idea about how it works or if it's related to this problem.
Note that I've tried swapping setInterval with setTimeout but it's the same result.
This is my JavaScript:
window.onload = function() {
clock();
function clock() {
var now = new Date();
var TwentyFourHour = now.getHours();
var hour = now.getHours();
var min = now.getMinutes();
var sec = now.getSeconds();
var mid = 'PM';
if (min < 10) {
min = "0" + min;
}
if (hour > 12) {
hour = hour - 12;
}
if (hour == 0) {
hour = 12;
}
if (TwentyFourHour < 12) {
mid = 'AM';
}
document.getElementById('time-core').innerHTML = hour + ':' + min;
setInterval(clock, 1000);
document.getElementById('time-suffix').innerHTML = mid;
setInterval(clock, 1000);
}
}
And this is my HTML:
<span class="show-time" id="time-core"></span><span class="show-time-suffix" id="time-suffix"></span>
Thank you!
As Andreas said in his comment:
Every call of clock() adds two new intervals that each will call clock(). So after the first round we then have two scheduled clock() calls, then 4, then 8, then ...
One way to solve that would be to remove the setInterval from inside the clock function, like the example below.
window.onload = function() {
clock(); // Run it first so we don't have to wait 1 second
setInterval(clock, 1000); // Updates the clock every second
function clock() {
var now = new Date();
var TwentyFourHour = now.getHours();
var hour = now.getHours();
var min = now.getMinutes();
var sec = now.getSeconds();
var mid = 'PM';
if (min < 10) {
min = "0" + min;
}
if (hour > 12) {
hour = hour - 12;
}
if (hour == 0) {
hour = 12;
}
if (TwentyFourHour < 12) {
mid = 'AM';
}
document.getElementById('time-core').innerHTML = hour + ':' + min;
document.getElementById('time-suffix').innerHTML = mid;
}
}

How do I pull javascript time other than from the user's device

I use a script that coverts Earth Time into an in-game time for a game (Eorzea Time). The script that was originally written is here.
My issue is that this pulls the Earth Time from the user's device clock. So if the clock is not correct on their device the conversion to Eorzea time is not accurate.
I'd like to pull Earth Time from a clock that is guaranteed to be accurate. I've been unable to figure out how to do this.
As an example. If you view this script alongside this site (www.ffxivclock.com) and change your time by even a minute or two...the jsfiddle clock will be off while the ffxivclock.com time will still be correct.
var E_TIME = 20.5714285714;
var global = {
utcTime: null,
eorzeaTime: null
};
window.setInterval(updateClock, Math.floor(1000 * 60 / E_TIME));
function updateClock() {
global.utcTime = new Date().getTime();
var eo_timestamp = Math.floor(global.utcTime * E_TIME);
global.eorzeaTime = new Date();
global.eorzeaTime.setTime(eo_timestamp);
showTime();
}
function showTime() {
var d = new Date();
d.setTime(global.eorzeaTime);
var eTime = document.getElementById('e-time');
var hours = d.getUTCHours();
var ampm = hours > 11 ? "PM" : "AM";
if(hours > 12)
hours -= 12;
hours = padLeft(hours);
var minutes = d.getUTCMinutes();
minutes = padLeft(minutes);
eTime.innerHTML = hours + ":" + minutes + " " + ampm;
}
function padLeft(val){
var str = "" + val;
var pad = "00";
return pad.substring(0, pad.length - str.length) + str;
}
updateClock();

Javascript/PHP countdown timer that updates every second and counts down to a specific date and time

So the code below is the code that I was able to work with so far; however, doesn't do exactly what I need it to do.
I want to be able to call a function (aka: sundayDelta() ), however, I would love to be able to define the day of week and time of day I want the function to use in the countdown inside the calling of the function. I'm not sure if this is possible...but I was thinking something like this
sundayDelta(1,1000) which would turn into Day of Week Sunday and time of day: 1000 (10:00am). Not sure if something like this is even possible; however, I'm hoping it is. I plan on having multiple countdowns going on the same page just appearing at different times of day.
When the countdown finishes, I want it to refresh a div (doesn't matter what name the div has)
I would also love to be able to incorporate PHP server time into this that way everyone is seeing the correct countdown no matter where they are.
Any help would be great! Thanks for your input!
function plural(s, i) {
return i + ' ' + (i > 1 ? s + 's' : s);
}
function sundayDelta(offset) {
// offset is in hours, so convert to miliseconds
offset = offset ? offset * 20 * 20 * 1000 : 0;
var now = new Date(new Date().getTime() + offset);
var days = 7 - now.getDay() || 7;
var hours = 10 - now.getHours();
var minutes = now.getMinutes() - 00 ;
var seconds = now.getSeconds()- 00;
if (hours < 0){
days=days-1;
}
var positiveHours= -hours>0 ? 24-(-hours) : hours;
return [plural('day', days),
plural('hour', positiveHours),
plural('minute', minutes),
plural('second', seconds)].join(' ');
}
// Save reference to the DIV
$refresh = $('#refresh');
$refresh.text('This page will refresh in ' + sundayDelta());
// Update DIV contents every second
setInterval(function() {
$refresh.text('This page will refresh in ' + sundayDelta());
}, 1000);
When I make flexible text for intervals, I like to subtract out until nothing is left. That way you only show the non-0 values:
function sundayDelta(target_date) {
var now = new Date();
var offset = Math.floor((Date.parse(target_date) - now.valueOf()) / 1000);
var r = [];
if (offset >= 86400) {
var days = Math.floor(offset / 86400);
offset -= days * 86400;
r.push(plural('day', days));
}
if (offset >= 3600) {
var hours = Math.floor(offset / 3600);
offset -= hours * 3600;
r.push(plural('hour', hours));
}
if (offset >= 60) {
var minutes = Math.floor(offset / 60);
offset -= minutes * 60;
r.push(plural('minute', minutes));
}
if (offset != 0) {
r.push(plural('second', offset));
}
return r.join(' ');
}
In the PHP code, you can set variable this way. And we'll leave time zones out of it for now, but they could be added as well just by specifying them.
echo "target_date = '" . date('Y-m-d H:i:s', strotime('next Sunday 10am')) . "';\n";

JavaScript code to run the Clock (date and time) four times faster

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);

Categories

Resources