I am trying to update information from a weather service on my page. The info should be updated every hour on the hour. How exactly do I go about calling a function on the hour every hour?
I kind of had an idea but I'm not sure of how to actually refine it so it works...
What I had in mind was something like creating an if statement, such as: (pseudo code)
//get the mins of the current time
var mins = datetime.mins();
if(mins == "00"){
function();
}
You want to check out setInterval: https://developer.mozilla.org/en-US/docs/Web/API/Window.setInterval
It's a little hard to tell what you're trying to call with your code, but it would be something in the form of:
function callEveryHour() {
setInterval(yourFunction, 1000 * 60 * 60);
}
If you want it every hour, try something like:
var nextDate = new Date();
if (nextDate.getMinutes() === 0) { // You can check for seconds here too
callEveryHour()
} else {
nextDate.setHours(nextDate.getHours() + 1);
nextDate.setMinutes(0);
nextDate.setSeconds(0);// I wouldn't do milliseconds too ;)
var difference = nextDate - new Date();
setTimeout(callEveryHour, difference);
}
Now, this implementation checks the time once, sets the delay (or calls the function immediately), and then relies on setInterval to keep track after that. An alternative approach may be to poll the time every x many seconds/minutes, and fire it .getMinutes() == 0 instead (similar to the first part of the if-statement), which may sacrifice (marginal) performance for (marginal) accuracy. Depending on your exact needs, I would play around with both solutions.
Here is what should work (JSFiddle):
function tick() {
//get the mins of the current time
var mins = new Date().getMinutes();
if (mins == "00") {
alert('Do stuff');
}
console.log('Tick ' + mins);
}
setInterval(tick, 1000);
What you probably want is something like that:
var now = new Date();
var delay = 60 * 60 * 1000; // 1 hour in msec
var start = delay - (now.getMinutes() * 60 + now.getSeconds()) * 1000 + now.getMilliseconds();
setTimeout(function doSomething() {
// do the operation
// ... your code here...
// schedule the next tick
setTimeout(doSomething, delay);
}, start);
So basically the first time the user get the access, you need to know what is the delay in millisecond to the next "hour". So, if the user access to the page at 8:54 (with 56 seconds and 123 milliseconds), you have to schedule the first execution after around 3 minutes: after the first one is done, you can call it every "hour" (60 * 60 * 1000).
Repeat at specific minute past the hour
This counter is a little bit more versatile; it allows to perform a task repeatedly always at the same minute past the hour (e.g. 37 minutes past the hour), and this with up to millisecond precision.
The precision of this timer is derived from its recursion.
At every recursion, the millisecond time to the next minute gets recalculated. This prevents time lag over long periods.
The % sign refers to the modulo operator.
function minuteCount(minutesAfterHour) {
const now = new Date();
const hours = now.getHours();
const minutes = now.getMinutes();
const seconds = now.getSeconds();
const milliseconds = now.getMilliseconds();
waitUntilNextMinute = setTimeout(minuteCount, 60000 - seconds * 1000 - milliseconds);
if(minutes % 60 === minutesAfterHour) {
doSomethingHourly();
}
}
minuteCount(37);
Finally, timers are best kept away from the main thread. They are best run from within a web worker, as explained here.
This works perfectly with unfocused tabs in desktop browsers.
However, dedicated web workers on Chrome for Android are put to sleep about 5 minutes after moving the main client to the background.
EDIT: Oops, I didn't see the " o' clock" things, so I edit my answer :
var last_execution = new Date().getTime();
function doSomething(force){
var current_time = new Date().getTime();
if (force || (current_time.getMinutes() == 0)
{
last_execution = current_time;
// something
// ...
}
setTimeout(doSomething(false), 1000);
}
// force the first time
doSomething(true);
// ... call your func now
let intervalId;
let timeoutId = setTimeout(() => {
// ... call your func on end of current hour
intervalId = setInterval(() => {
// ... call your func on end of each next hours
}, 3600000);
}, ((60 − moment().minutes()) × 60 × 1000) - (moment().second() * 1000));
Here is my pair of setIntervalWithDelay and clearIntervalWithDelay that one can use like this:
let descriptor = setIntervalWithDelay(callback, 60 * 60 * 1000, nextHourDelay)
And when you are done with it:
clearIntervalWithDelay(descriptor)
Here is my implementation of the functions:
const setIntervalWithDelay = (callback, interval, delay = 0) => {
let descriptor = {}
descriptor.timeoutId = setTimeout(() => {
if(!descriptor.timeoutId){
return
}
descriptor.timeoutId = null
callback()
descriptor.intervalId = setInterval(callback, interval)
}, delay)
return descriptor
}
export const clearIntervalWithDelay = (descriptor) => {
if(!isObject(descriptor) || (!descriptor.timeoutId && !descriptor.intervalId)){
console.warn("clearIntervalWithDelay: Incorrect descriptor. Please pass an object returned by setIntervalWithDelay. Skipping this call.")
return
}
if(descriptor.timeoutId){
clearTimeout(descriptor.timeoutId)
descriptor.timeoutId = null
console.log("clearIntervalWithDelay: stopped during delay.")
}
if(descriptor.intervalId){
clearInterval(descriptor.intervalId)
descriptor.intervalId = null
console.log("clearIntervalWithDelay: stopped during interval repeat.")
}
}
One example of using dayjs to get the delay for the next hour:
let nextHour = dayjs().second(0).millisecond(0).add(1, "hour")
let nextHourDelay = nextHour.diff(dayjs())
Related
I am creating a website for students which will be used to assign exams and I am having difficulties with the timer. The one I am using is made on the frontend in javascript and whenever the page is refreshed the timer startsover. Tried to store the start and end date by converting to epoch and back to datetime but I cannot think of a way to get the timer to the frontend and start counting. The idea is to count 60 minutes and call the submit button as well as to show the countdown without the option to restart the counter.
This is how I store the start and end time in nodejs.
var myDate = new Date();
var startTimeEpoch = myDate.getTime()/1000.0;
var endTimeEpoch = startTimeEpoch + 5400 // Adding 90 minutes to the timer
var startTimeBackToDate = new Date(startTimeEpoch *1000)
var endTimeBackToDate = new Date(endTimeEpoch *1000)
This is the javascript timer I am using and I am wondering if I should use one in the first place.
function startTimer(duration, display) {
var start = Date.now(),
diff,
minutes,
seconds;
function timer() {
diff = duration - (((Date.now() - start) / 1000) | 0);
minutes = (diff / 60) | 0;
seconds = (diff % 60) | 0;
minutes = minutes < 10 ? "0" + minutes : minutes;
seconds = seconds < 10 ? "0" + seconds : seconds;
display.textContent = minutes + ":" + seconds;
if (diff <= 0) {
start = Date.now() + 1000;
}
}
timer();
setInterval(timer, 1000);
}
window.onload = function () {
var fiveMinutes = "<%= scenario.time %>" * 60,
display = document.querySelector('#time');
startTimer(fiveMinutes, display);
}
As a general response and with the additional information provided, i could propose a solution to make this work.
If your students all have a specific exam entity attached to them, when they register/start an exam, you could retrieve the start date of this exam(add a mongo createdAt Date field) and use it as the starting date.
If each exam has a time limit, then you could simply do the math to know how much time is left. Something that will look like this:
const getExamRemainingTime = (exam) => {
// assuming that start is a js date object
// and timeLimit is an number representing the duration hours of your exam
const { start, timeLimit } = exam;
let end = (start.getHours() + timeLimit);
end = end.setHours(end);
const remainingTime = (+end) - (+start)
if (remainingTime > 0) {
// duration not finished, exam still in progress
return new Date(remainingTime);
} else {
// exam finished
return 0;
}
}
Then in your frontend, if it's plain javascript, you need to refresh your timer component, use setInterval in last ressort because it's very heavy on performance and format the date you got the way you want to show it.
Ref: casting js Date object to timestamp - How do you get a timestamp in JavaScript?.
I don't think a timer that a student with Javascript knowledge can modify should be used for serious tests, but for anything more light-hearted it should be fine.
The best system I can think of for this would be to have the test length stored in the mongodb and when a signed-in user starts the test, have the current time logged for that user. That way, you can calculate time remaining using user.testStart + test.length - Date.now().
I need to run my javascript timer in every 5 seconds, but only then, when the current time is at "round" 5 seconds (I mean when the second value is divisible by 5.) So, I want to set the start time to "round" 5 seconds.
Not good, when the second is (for example): 7, 12, 17, 22 etc ...
Good: 0, 5, 10, 15 etc ...
My current code (runs well in every 5 seconds, but the start is not set to "round" 5 seconds):
<script type="text/javascript">
window.setInterval(function(){
draw();
}, 5000);
</script>
Please, help me.
Get the actual date and extract seconds*1000 and milliseconds. Modulo 5.000 gets ms from last 5s interval subtract this from 5.000 and you get the first start.
Start the first time with setTimeout and after this every 5.000 ms with setInterval.
let date = new Date();
let ms = date.getSeconds()*1000 + date.getMilliseconds();
let start = 5000 - (ms %5000);
//console.log(ms, start);
setTimeout(function(){
doIt();
window.setInterval(doIt, 5000);
}, start);
function doIt() {
console.log('Boom');
}
You can do a loop every 1 sec, to check if modulus of getUTCMinutes() / 5 == 0, and once it does, then execute your script.. so it will START at that 5 min mark, and then continue on it's own..
Use recursive setTimeouts instead, which measures the time between now and the next "round" seconds number:
const scheduleDraw = () => {
const now = new Date();
const secondsToNext = 5 - (now.getSeconds() % 5);
const millisecondsToNext = ((secondsToNext - 1) * 1000) + (1000 - now.getMilliseconds());
setTimeout(draw, millisecondsToNext);
};
const draw = () => {
console.log('drawing at', new Date());
scheduleDraw();
};
scheduleDraw();
Don't use setInterval - it'll get inaccurate after a while, especially if the user switches browser tabs. Better to calculate the new timeout every time.
The idea is to have a function that reads out the system time, and determines how much time is left for the next 5 second moment, and triggers a corresponding setTimeout for that.
You should allow for a few milliseconds of variation though:
function callAt5(callback) {
let now = new Date();
let milli = (now.getMilliseconds() + 1000 * now.getSeconds()) % 5000;
setTimeout(callAt5.bind(null, callback), 5000 - milli);
if (milli < 100) callback();
}
// pass the callback which you want to execute at each 5 second mark:
callAt5(() => console.log(new Date));
I'm creating pomodoro timer- interval should repeat with different duration after first one completes. simplified non working exampe:
var firstDuration=5;
var secondDuration=10;
var timer=setInterval(()=>{
firstDuration--
if (firstDuration<0){
clearInterval(timer) ..
//secondDuration-- dont know how to continue..
What is the best way to implement such functionality? Also i plan to use Date.now() rather than -- .
If i've understood the requirements correctly, this will do what you want. It will have a timer go off every second until 20 minutes have elapsed, then every second until 5 minutes have elapsed. At that point it starts over with the 20 minute countdown.
const workDurationSeconds = 20 * 60;
const breakDurationSeconds = 5 * 60;
function startCountdown(session) {
let duration;
if (session === 'work') {
duration = workDurationSeconds;
} else {
duration = breakDurationSeconds;
}
let id = setInterval(() => {
duration--;
if (duration <= 0) {
clearInterval(id);
startCountdown(session === 'work' ? 'break' : 'work');
}
}, 1000);
}
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'm trying to compare to 2 dates by hour/minutes/seconds, in order to make a script to resume a script when closed. If current time is pass closed time + interval ( currently set at 30 minutes) should execute and run the script normally, if not wait till difference timeouts to execute.
Current hour/minutes/seconds is not a must but the result should be in ms interval
Example:
interval = (30 * 60 * 1000)
close time = 15:10:53
current time = 15:15:29
close time + interval = 15:40:53
first time I check if `current time` <= `close time + interval`
then calculate `difference`
`difference` = (close time + interval = 15:40:53) - (current time = 15:15:29)
Result should be setTimeout(function(){ alert("Hello"); }, time difference);
The only way I'm thinking of doing this is calculate each difference from Hour,Minutes,Seconds and then finding out the ms for setTimeout
I tried but results were weird, not something that would count as smaller than 30min
var ONE_S = 1000 ;
var timeDiff = Math.abs(closeTime - currentTime);
var diffS = Math.round(timeDiff/ONE_S)
Use Date objects and compare timestamps like so:
var interval = 30 * 60 * 1000;
var closeTime = new Date('Wed Nov 26 2015 10:17:44 GMT-0400 (AST)');
var currentTime = new Date;
var difference = (closeTime - currentTime) + interval;
if(difference < 0) {
console.log('time has expired');
}else{
setTimeout(someFunction, difference);
}
closeTime - currentTime gets the time between timestamps in ms, which will be negative if it's past closing time. We offset closing time by 30 minutes (by adding interval). Then we just have to check if difference < 0 to know if time has expired, and if not we can wait difference milliseconds to trigger someFunction