how to calcuate seconds left in the current minute of the time - javascript

I want to update a clock in the UI when the time changes from 12:01 to 12:02.
I can do a setInterval every 60 seconds, but the beginning might not be on the first second of a new minute. How can I ensure that it starts at the first second?
I think I need to find out how many seconds are left in the current minute and then do a setTimeout that fires setInterval when the seconds elapse.
var secondsLeft = ?; //calculate seconds left in this minute
setTimeout(function(){
setInterval(function(){
//update clock
}, 1000 * 60);
}, secondsLeft);
If moment.js makes it easier, that's fine with me.

Try this: secondsLeft = 60 - new Date().getSeconds()

I would store old value, use requestAnimationFrame to see if browser is ready to render and at the render check if the minute has changed from previous render.

Related

ReactJS: Continue timer in the background?

I have a create-react-app that has a setInterval that runs a tick() function every 1000 millisecond. The tick() function decrements the sessionTime state by one. It works perfectly fine when the browser tab is in the foreground but it loses count in the background (not counting after a certain period). How do I allow it to continue running? Is this even the right approach to a timer in React?
You might be running out of your time budget?
Anyway, a more reliable way is not to rely on the interval being a specific time; check current new Date() every time you execute your tick, calculate how much time has passed since last tick or since a certain remembered start time (or remaining to certain target time), and act accordingly.
For example, if you want a session to expire in 30 minutes,
let now = new Date();
const second = 1000;
const minute = 30 * second;
let expiryTime = new Date(now.getTime() + 30 * minute);
and then in your tick just check whether new Date() > expiryTime. This way, it does not matter how often your tick routine runs.

jQuery timer stops if user is not using browser

I am trying to build a jQuery timer, but it stops when the browser is not focused or minimized. One of my thoughts is the code can use Ajax to pull data constantly from the server and update the timer, but my concern is that it may increase the pressure of the server. I wonder is there any way to check if user is using browser at frontend, so the code only needs to send Ajax request once the user returns.
My jQuery timer code snippet.
(function timer (offset) {
setTimeout(function () {
var timestamp = {{ time }};
timestamp = 5 * 60 - timestamp - offset;
var minutes = Math.floor(timestamp / 60);
var seconds = Math.floor(timestamp % 60);
document.getElementById("timer").innerHTML = minutes + " : " + seconds;
timer(offset + 0.5);
}, 500);
})(0);
window.setTimeout's delay parameter is the minimum amount of time before the callback runs, not a guaranteed time. Instead of keeping a running total of time elapsed in the timeout, store the time the timer started and compare it to the current time. Performance.now() will give you an accurate timestamp measured in milliseconds.

CodeHS JavaScript Timer- Countdown

I work on CodeHS and need to make a countdown timer for my powerups in the game I'm making, Breakout. I need the timer to be reusable so no for loops, it needs to go down in seconds/milliseconds (it doesn't matter which) and preferably last 30 seconds or 30,000 milliseconds. Remember this is CodeHS I'm working on.
If you want something to happen 30 seconds after you start your timer you could do something like this:
//set the time remaining to 30 outside of a function so it is global
var timeRemaining = 30;
function start(){
//set the timer to run the function countdown once every second(1000 milliseconds)
setTimer(countdown, 1000)
}
function countdown(){
/*every time it is called this function subtracts one from the time if it is
more than 30, when it reaches 0 stops the timer and resets the time*/
if(timeRemaining<=0){
stopTimer(countdown);
timeRemaining = 30;
println("Done");
//30 seconds has passed, do what you need here(call your function)
}else{
timeRemaining--;
println(timeRemaining+" seconds left")
}
}
Add your function or whatever you want to happen after the time is up whereprintln("Done") is.
Because timeRemaining is set back to 30 at the end, you can reuse the timer by calling setTimer(countdown, 1000) again.
You can remove the println statments, they are just to see what is happening.
If CodeHS doesn't want hardcoded numbers (I think they call them "magic numbers"), replace the 30s with a constant set to 30.
Let me know if you need a better explanation.
Tell me if I'm wrong because I have no idea what CodeHS is, but I am quite sure that this can be achieved with a simple setInterval function.
To go by full seconds:
var timer=30;
setInterval(function(){
timer-=1;
document.getElementById(timerId). innerHTML=timer;//shows the remaining time
}, 1000);//subtracts 1 second from timer each second
To go by tenths of a second
var timer=30.0;
setInterval(function(){
timer-=0.1;
document.getElementById(timerId). innerHTML=timer;//shows the remaining time
}, 1000);//subtracts a tenth second from timer every 0.1 seconds
var timeLeft = 60;
var txt = new Text(" ","30pt Arial");
function start(){txt.setPosition(200,200); txt.setColor(Color.black); add(txt); setTimer(countdown,1000);}
function countdown(){drawTimer(); timeLeft--;}
function drawTimer(){txt.setText(timeLeft);}

Run JS function every new minute

So I've got this JavaScript clock I'm working on and I want it to be perfectly synced with the clients' system clock. I know how to get the current time using a Date object and I know how to run the update function every 60000 milliseconds (1 minute). The thing is that the client might load the page when half a minute has already passed, making the clock lag behind with 30 seconds. Is there any way to just run the update function when the minute-variable actually changes? (I only want minute-precision.)
How I get the current time:
var time = new Date();
var currentHour = time.getHours();
var currentMinute = time.getMinutes();
How I run the update function every 60000 ms:
setInterval(update,60000); //"update" is the function that is run
When the user logs in, get the current time and seconds of the minute, subtract 60 to get the remaining seconds, then multiply to set the timer
var time = new Date(),
secondsRemaining = (60 - time.getSeconds()) * 1000;
setTimeout(function() {
setInterval(update, 60000);
}, secondsRemaining);
First, you have to understand that timers in javascript are not guaranteed to be called on time so therefore you cannot be perfectly synced at all times - javascript just isn't a real-time language like that. It is single threaded so a timer event has to wait for other javascript that might be executing at the time to finish before a timer can be executed. So, you must have a design that still does as best as possible even if the timer is delayed (called later than it's supposed to be).
If you wanted to try to stay as close to aligned and do the fewest screen updates and be the most friendly to mobile battery life, I'd suggest this self-aligning code which realigns itself on each tick based on the time remaining until the next minute change:
function runClock() {
var now = new Date();
var timeToNextTick = (60 - now.getSeconds()) * 1000 - now.getMilliseconds();
setTimeout(function() {
update();
runClock();
}, timeToNextTick);
}
// display the initial clock
update();
// start the running clock display that will update right on the minute change
runClock();
This has the advantage that it only calls the update once on the next minute boundary.
Working demo: http://jsfiddle.net/jfriend00/u7Hc5/
var time = new Date();
var currentHour = time.getHours();
var currentMinute = time.getMinutes();
var currentSecond = time.getSeconds();
var updateinterval = setInterval(startTimer,(60-currentSecond)*1000);
function startTimer(){
clearInterval(updateinterval);
setInterval(update,60000);
}
function update(){
var time = new Date();
console.log(time.getSeconds());
}
I would set an interval to run each second, then check if time.getSeconds() == 0. This way you could execute an action whenever a new minute starts, based on the client time.

How can I make a javascript/jQuery countdown that is only visible after X minutes?

After the users have been inactive for X minutes, I need to display the number of minutes left till the session times out in ASP.NET.
For e.g. after 5 minutes, they will see 'You have been inactive for 5 minutes. You will be logged off after another 10 minutes'. Each minute after that, the message will be updated.
I found a jQuery plugin called 'jQuery Countdown', but how can I make it visible only after X minutes have passed?
When the page loads, I will use RegisterStartupScript while passing Session.Timeout as a parameter to this function.
Thanks for your help.
You could fade it in after 5 minutes using .delay() like this:
$("#timer").delay(299600).fadeIn(function() { // 5 * 60 * 1000 - 400ms for fade
$(this).countdown({ ... countdown options ... });
});
This is basically just doing a setTimeout() behind the scenes on the queue, just a short/simple way of doing the same. That being set, setTimeout(showFunc, 300000) will do the job just fine.
you can use a regular javascript setTimeout function
and set it to 5 minutes...
and put a function there that will make your countdown visible
var interval = setInterval(displayInactiveMessage, 300000);
300000 = 5 minutes in milliseconds.
Then clearInterval(interval) to stop it from running every 5 minutes.
Yo can you the same mechanism for you 1 minute updates - just don't clear it.

Categories

Resources