I'm trying to make a game clock where each game hour are 3 real-time minutes. But I have a hard time wrapping my head around it for some reason.
I've came up with this half working bit, with a loop of 3 minutes for each hour so it's only showing full 'game hours' which I reset once above 23 to start a fresh day.
I guess I would have to update the loop to the accuracy of the game time clock?
var hours;
if (process.argv.length > 2) {
// setting the clock
hours = parseInt(process.argv.slice(2));
}
console.log(hours);
let timerId = setInterval(function() {
hours = hours + 1
if (hours > 23) {
hours = 0;
}
console.log(hours);
}, 3 * 60 * 1000);
Yes, you would have to have a much faster repeating interval, at the level of game-seconds. If one game-hour is 3 real minutes, then game time actually runs 20 times as fast as real time, and so one game-second would last 1/20 real seconds, i.e. 50 milliseconds.
const speed = 20; // how many times faster than real time
let clockDiv = document.querySelector("#clock");
let gameStartTime = 0; // game-milliseconds;
let realStartTime = Date.now(); // real milliseconds
let timerId = setInterval(function() {
let gameTime = gameStartTime + (Date.now() - realStartTime) * speed;
let sec = Math.floor(gameTime / 1000) % 60;
let min = Math.floor(gameTime / 60000) % 60;
let hour = Math.floor(gameTime / 3600000) % 24;
// output in hh:mm:ss format:
clockDiv.textContent = `${hour}:${min}:${sec}`.replace(/\b\d\b/g, "0$&");
}, 50);
<div id="clock"></div>
I'm entirely sure where your problem is, but # 3 mins real time = 1 hour game time, 1 real second = 20 game seconds. 3600 / 180 = 20. You should be able to feed the game seconds into any normal time function to get minutes/hours etc.
Related
I'm trying to create a countdown that repeats every 24, 48 or 72 hours at midnight without moment.js
For example (example for 48 hours):
10-12-22 00:00 -> start countdown -> 47:59:59
11-12-22 22:30 -> countdown = 1:30:00
12-12-22 00:00 -> the countdown restart -> 47:59:59
I try solution only for 24 hours
I try this:
setInterval(function time() {
var d = new Date();
var hours = 24 - d.getHours();
var min = 60 - d.getMinutes();
if ((min + '').length == 1) {
min = '0' + min;
}
var sec = 60 - d.getSeconds();
if ((sec + '').length == 1) {
sec = '0' + sec;
},
1000);
There are a huge number of questions and answers already about timers and countdowns. Pick one.
The only point of interest here is that it should to restart when the remainder gets to zero, e.g.:
// Counts down period milliseconds, then restarts
function timer(period) {
let start = new Date();
let z = n => ('0'+n).slice(-2);
let zz = n => ('00'+n).slice(-3);
let f = ms => {
let day = (ms / 8.64e7) | 0;
let hr = (ms % 8.64e7) / 3.6e6 | 0;
let min = (ms % 3.6e6) / 6e4 | 0;
let sec = (ms % 6e4) /1e3 | 0;
let mil = (ms % 1e3);
return `${day} days, ${z(hr)}:${z(min)}:${z(sec)}.${zz(mil)}`;
}
setInterval(() => {
console.log(f(period - (Date.now() - start) % period));
}, 1000);
}
timer(1000*5);
Format the output however you want, maybe floor the seconds and ditch the milliseconds.
BTW, setInterval is not a good way to run a timer. Use successive calls to setTimelout with the lag set to about 10ms longer than the time to the next full second, minute or whatever. That way it won't be seen to miss a second (which happens with setInteval because it may slowly drift, as can be seen in the ms part of the above, there is always at least 1e3 ms between logs, usually more and sometimes a lot more, depending on how busy the system is with other tasks).
I don't really get the question but perhaps try setInterval?
//this will log to console after 2 days
setInterval(() => {
console.log("Ding Dong");
},
2*24*60*60*1000);
I am trying two create to separate timers. One timer counts down to a date and displays a countdown and the other counts down on an interval and resets (ie: 5 hours and resets).
The one I am having trouble with is the second option. I am trying to create a countdown that is relative to real-time and then resets once it reaches zero. So for example setting it to 2 days and 5 hours. Once this completes the clock resets to 2 days 5 hours. I am having trouble getting the clock to reset at the specified time and loop without having negative numbers. I tried this two separate ways but feel like I am over-complicating things.
The reason I use real-time is so that the clock will be the same if you open it in another tab. If I create a regular timer it will reset upon refreshing the page.
codpen
In this example I tried to reset the counter every 40 seconds but couldn't get it to work. Ultimately I want to be able to specify the date with ie: 00:12:00 (12 hours countdown) and then have it reset automatically. I just can't figure out how to maintain the counting without going to negative numbers or freezing it.
function timer() {
var currentTime = new Date()
var date = currentTime.getDate()
var hours = currentTime.getHours()
var minutes = currentTime.getMinutes()
var seconds = currentTime.getSeconds()
var daysLeft = 0;
var hoursLeft = 24 - hours;
var minsLeft = 60 - minutes;
var secsLeft = 60 - seconds;
// counter freezes at 40 seconds and hangs for 20seconds
if(secsLeft => 40) {
secsLeft = 40 - seconds
if(secsLeft < 0) {
secsLeft = 40
}
}
document.getElementById('timerUpFront').innerHTML= "<br><br><strong>Duration Countdown with Infinite Reset #2</strong><br>" + daysLeft + " days " + hoursLeft + " hours " + minsLeft + " minutes " + secsLeft + " seconds";
}
var countdownTimer = setInterval('timer()', 1000);
codpen
you can separate the timer to functions to simplify it and apply the following logic
function startTimer () {
val targetRemainedSeconds = // calculate the value
val remainedSeconds = targetRemainedSeconds
setInterval(timer(), 1000)
}
function timer () {
remainedSeconds--
if (remainedSeconds < 0) reaminedSeconds = targetReaminedSeconds // reset the timer
timerUpdate()
}
function timerUpdate() {
// use 'remainedSeconds' to update timer
}
I am trying to make a small question/answer quiz game using react, and I want to show a timer that counts down every second. Each game will last 10, 15, or 30 minutes at most, so I want to show a timer that updates every second in the bottom of the screen (in big font, of course!), something like 15:00, 14:59, 14:58, and so on until it hits 00:00.
So, given a start time such as 2016-04-25T08:00:00Z, and an end time after adding 15 min of 2016-04-25T08:15:00Z, I want to start the countdown.
My issue is that I am not understanding how to use setIntervals to keep calling my method to find the remaining time.
timeLeft = Math.round(timeLeft/1000) * 1000;
const timer = new Date(timeLeft);
return timer.getUTCMinutes() + ':' + timer.getUTCSeconds();
EDIT: You've edited your question. You will need the time padding, and the method below will be faster than what you are using, but to answer your question about setInterval:
First, define your function to run your timer and decrement each time it's called:
var timeLeft; // this is the time left
var elem; // DOM element where your timer text goes
var interval = null; // the interval pointer will be stored in this variable
function tick() {
timeLeft = Math.round(timeLeft / 1000) * 1000;
const timer = new Date(timeLeft);
var time = timer.getUTCMinutes() + ':' + timer.getUTCSeconds();
elem.innerHTML = time;
timeLeft -= 1000; // decrement one second
if (timeLeft < 0) {
clearInterval(interval);
}
}
interval = setInterval(tick, 1000);
OG Answer:
No, I do not believe there is a built-in way to display time differences.
Let's say you have two date objects:
var start = Date.now();
var end = Date.now() + 15 * 60 * 1000; // 15 minutes
Then you can subtract the two Date objects to get a number of milliseconds between them:
var diff = (end - start) / 1000; // difference in seconds
To get the number of minutes, you take diff and divide it by 60 and floor that result:
var minutes = Math.floor(diff / 60);
To get the number of seconds, you take the modulus to get the remainder after the minutes are removed:
var seconds = diff % 60;
But you want these two padded by zeros, so to do that, you convert to Strings and check if they are two characters long. If not, you prepend a zero:
// assumes num is a whole number
function pad2Digits(num) {
var str = num.toString();
if (str.length === 1) {
str = '0' + str;
}
return str;
}
var time = pad2Digits(minutes) + ':' + pad2Digits(seconds);
Now you have the time in minutes and seconds.
I made this function that does two things: returns the amount of time until the next thirty minute mark, and calls the halfHour function when the timer reaches zero. If the time was 12:06:27, output would be 24:33 (mm:ss)
function checkTime() {
var time = new Date();
var mins = time.getMinutes();
mins = (60-mins) % 30;
var secs = time.getSeconds();
if (secs != 60){
secs = (60-secs) % 60;
} else {
secs = 00;
}
time = [Number(mins),Number(secs)];
if (mins == 0 && secs == 0){
halfHour();
}
return time;
}
This works, but there is a strange glitch. When the minute rolls over, it shows...
24:02
24:01
23:00
23:59
23:58
It also calls halfHour(); one minute too soon, at the false 0:00 mark in the last sequence: 1:02 1:01 0:00 0:59
How can we correct this?
Solved
Commenters dbrin and njzk2 have the solution. It's subtracting minutes and seconds from 59 instead of 60. Below is the modified working code. Sorry it's messy.
function checkTime() {
var time = new Date();
var mins = time.getMinutes();
mins = (59-mins) % 30;
var secs = time.getSeconds();
if (secs != 60){
secs = (59-secs) % 60;
} else {
secs = 00;
}
time = [Number(mins),Number(secs)];
if (mins == 0 && secs == 0){
halfHour();
}
return time;
}
Why reinvent the wheel when JavaScript has a built in setInterval(code, delay); to acheive this.
setInterval(function() {
alert("I will fire after every 2 seconds")
}, 2000);
The way you measure the time is flawed. The number of minutes and the number of seconds cannot be considered separately, as I showed in my earlier comment.
An easier way is to start by measuring the total number of seconds, and then format it:
var time = new Date();
var totalS = 60 * ((60 - time.getMinutes()) % 30) - time.getSeconds()
var secs = totalS % 60
var mins = (totalS - secs) / 60
Currently I am working on JavaScript, jQuery, HTML5 to improve myself. I have a opensourcely coded clock, which I have converted it into a counter (reverse counter).
Problem I am having is, in my setInterval(){...} I have four variables -> second,min,hour, and day. The problem is, when I get the seconds, I get something like 1.155, 2.312, 3.412 (seconds).
My setInterval function is below
setInterval(function(){
//var duration = parseInt(Date.now() /1000 ) - 1365470000;
var futureTime = Date.parse('April 10, 2013 22:00:00');
var duration = (( parseInt(Date.now() - futureTime ) / 1000));
var seconds = duration % 60;
duration = parseInt(duration / 60);
var minutes = duration % 60;
duration = parseInt(duration / 60);
var hours = (duration)%24;
duration = parseInt(duration / 24);
var days = duration % 365;
animation(gVars.green, seconds, 60);
animation(gVars.blue, minutes, 60);
animation(gVars.orange, hours, 24);
animation(gVars.red, days, 365);
},1000);
}
And my output is below for some random time since i use parseInt(Date.now()).
I have to give the link since I don't have enough rep.
http://i.stack.imgur.com/0Zkbi.png
How can I get rid of the decimal point in setInterval(){} functions?
Thanks in advance.
JavaScript offers more convinient API to work with date and time in order to fetch seconds, minutes, hours and days. Try this code:
var duration,
seconds,
minutes,
hours;
duration = new Date((new Date('April 11, 2013 23:00:00')) - (new Date()));
seconds = duration.getSeconds();
minutes = duration.getMinutes();
hours = duration.getHours();
Now you will have integer values in all 4 variables above, without any decimal point.
var seconds = 1234.13;
var seconds = seconds + '';
seconds = seconds.split('.')[0];
console.log(seconds);