This loop works:
var time;
for (time = 0; time < 5; time++) {
// Runs 5 times
console.log('Log');
}
But this doesn't:
var time;
for (time = 1490543999999999; time <= time - (518400000000 * 10) ; time = time - 518400000000) {
console.log('Log');
}
How come? Is it because the numbers are too large? How to solve this problem then?
Two differences with the first loop:
Since you are traversing in the opposite direction, you need the opposite comparison for the loop condition: > instead of <=.
As you change the time variable, you cannot use it as boundary value. Use a different variable for that -- one that does not change from the initial value
var time, initTime;
for (initTime = time = 1490543999999999; time > initTime - (518400000000 * 10) ; time = time - 518400000000) {
console.log('Log');
}
Or better (to avoid recalculation of the limit):
var time, endTime;
for (time = 1490543999999999, endTime = time - 518400000000 * 10; time > endTime; time -= 518400000000) {
console.log('Log');
}
Related
I have a working timer, but it runs from 25 seg every time who the website is visited by a client, I want to synchronise it. F.E. if i visit my webpage in mY Pc, and when it show 15seg left, i visit it from other pc and i want it to show 15 left too.
function timerr(){
var initial = 25000;
var count = initial;
var counter;
var initialMillis;
function timer() {
if (count <= 0) {
clearInterval(counter);
return;
}
var current = Date.now();
count = count - (current - initialMillis);
initialMillis = current;
displayCount(count);
function displayCount(count) {
var res = count / 1000;
if (res<0.1){
document.getElementById("timer").innerHTML = "";
}
else{
tiempo = res.toPrecision(count.toString().length);
tiempo_corto = tiempo.slice(0,-1);
document.getElementById("timer").innerHTML = tiempo_corto;
}
}
clearInterval(counter);
initialMillis = Date.now();
counter = setInterval(timer, 10);
}
If you want everyone to have the same timer count down every 25 seconds and stop at the exact same time, then you can simply use timestamps to keep everything in sync. Here's an example countdown timer that'll restart every 6 seconds (from 5 to 0) and will hit zero at the exact same time for everyone (unless their computer clock is off).
const timerElement = document.getElementById('timer')
const TIMER_DURATION = 6
function step() {
const timestamp = Date.now() / 1000
const timeLeft = (TIMER_DURATION - 1) - Math.round(timestamp) % TIMER_DURATION
timerElement.innerText = timeLeft
const timeCorrection = Math.round(timestamp) - timestamp
setTimeout(step, timeCorrection*1000 + 1000)
}
step()
<p id="timer"></p> seconds
Try it - open this page up in two different tabs and run it. This is set up to automatically account for the fact that setTimeout doesn't always trigger at the delay you asked it to do so (it'll adjust the next setTimeout with a timeCorrection value to correct these issues).
The basic principle is that we're getting the current timestamp and modding it by the amount of time we want this timer to last (6 seconds in the above example). This value will always be the same for everyone, and will always be a number that ranges from 0 to 5. It will also be a number that counts up every second (which is why we then subtract (TIMER_DURATION - 1) from it, to cause the number to count down instead).
Here are some of the variables I have:
start time: 10:45
interval time: 5 (in minutes)
specific time: 14:20
I need to find out if the specific time lands exactly on any of the times incremented from the start time.
For example, the interval time is 5.
10:45 incremented by interval time
11:00
11:05
11:10
...
14:20 << specific time found
if(specificTime is mentioned in any of the incremented times) {
console.log('Found it!');
} else {
console.log('Not found');
}
But this is hard when the start time is 10:48 and the interval time is 5 minutes. Because:
10:48
10:53
10:58
11:03
11:08
...
and 14:20 is not mentioned in this one, so it would log "Not found".
How can I find out if the specific times is mentioned in the incremented times from the start time?
The interval time will not always be 5 and the other variables will be dynamic as well.
I am NOT looking to use loops. There has to be a formula or function that can help me achieve this. Thanks!
I think you can calculate if it is possible to perform a restless division of the difference between the start time and the specified time and the interval.
Depending on the scale of your time intervals, you can calculate this in hours, minutes, seconds, milliseconds or basically any scale. Since your examples deal in minutes, the code snippet also does.
Note that this snippet assumes both times are within the same day (00:00 - 24:00) and that the specific time is later within that day than the start time. I'll let you figure out the rest :)
function toMinutes(hours, minutes) {
return (hours * 60) + minutes;
}
const startTime = toMinutes(10, 45);
const specificTime = toMinutes(14, 20);
const interval = toMinutes(0, 5);
const difference = specificTime - startTime;
if (difference % interval === 0) {
console.info('Found it!');
console.info('Minutes:', difference);
console.info('Intervals:', difference / interval);
} else {
console.error('Not found');
}
This works by:
- Turning the time strings into numeric minutes (with countOfMinutes())
- Subtracting startTime from specificTime (and adjusting if we increment past 12:00)
- Dividing the result by minsPerIncrement and checking whether the remainder is zero
// The big payoff -- calculates whether we exactly hit `specificTime`
function isExact(start, specific, increment){
let difference = countOfMinutes(specific) - countOfMinutes(start);
if(difference <= 0){ difference += 12 * 60; } // Add 12 hours if necessary
return difference % increment == 0;
}
// The converter -- because numbers are easier to divide than strings
function countOfMinutes(timeString){
const hours = timeString.slice(0, timeString.indexOf(":"));
const mins = timeString.slice(timeString.indexOf(":") + 1);
return hours * 60 + mins;
}
// The results -- some readable output
function report(){
console.log(`
Repeatedly adding ${minsPerIncrement} to ${startTime} will eventually yield ${specificTime}?:
_ ${isExact(startTime, specificTime, minsPerIncrement)} _`);
}
// The pudding -- a couple of test cases
let start, specific, minsPerIncrement;
startTime = "12:30"; specificTime = "3:55"; minsPerIncrement = 21;
report();
startTime = "4:20"; specificTime = "11:45"; minsPerIncrement = 5;
report();
startTime = "11:45"; specificTime = "4:20"; minsPerIncrement = 5;
report();
Im trying to wrap my head around this function. Mainly the NewTime=time-lastTime; line. Why is it needed? What exactly does it do? From what I gather ir takes the elapsed start time which increments starting at zero. Then takes away the last time we saw which will always leave me with the difference of the two times. But how does it use this to update?
let Count = 0;
let interval = 500;
let lastTime = 0;
function update(time = 0) {
const NewTime = time - lastTime;
lastTime = time;
Count += NewTime;
if (Count > interval) {
player.pos.y++;
Count = 0;
}
draw();
requestAnimationFrame(update);
}
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 am creating an application that uses a timer to draw lines to several canvases while updating stats to DIVs. In order to create the smoothest animation possible I've had to set the setInterval() timer to the smallest delay possible, which from my understanding, is between 10-15 milliseconds across browsers.
The issue I am having is with the stopwatch that tracks the scenarios running time. The stopwatch itself works well enough as I have established using console.log, however, the setInterval() timer slows down when I try to update the DOM element. This has lead me to believe that in combination with the small timer tick delay there is a performance issue with the way I am updating the DOM element.
Code:
function draw() {
var drawTimer = setInterval(drawStuffTest, 15);
var timer = doc.getElementById('time');
var milliseconds = 0;
var seconds = 0;
var minutes = 0;
function updateTimer() {
//clear the old elapsed time
timer.innerHTML = "";
milliseconds += 15;
//increment seconds
if (milliseconds >= 1000) {
seconds++;
milliseconds = 0;
}
//increment minutes
if(seconds >= 60)
{
seconds = 0;
minutes++;
}
//Pad minutes and seconds with leading zeroes if either is lest than 10
var secondsString = ( seconds < 10 ? "0" : "" ) + seconds;
var minutesString = ( minutes < 10 ? "0" : "" ) + minutes;
var elapsedTime = minutesString + ":" + secondsString;
/* The timer works fine when I just use console.log to display the
timer however once I add the following statement to update the DOM
element the timer slows down */
//timer.innerHTML = elapsedTime;
console.log(elapsedTime);
}
Does anyone have any suggestions?