Javascript date + milliseconds - javascript

I am working on a pause function for a timer I have built and I am getting a little stuck.
As soon as the timer starts, I capture the current date in milliseconds:
if(!begin){
begin = Date.now();
}
Once the user has clicked pause, it will then get the current date in milliseconds.
// Pause the timer
function pause(){
console.log('Begin : ' + begin) //Begin : 1467580324524
console.log('End: ' + currentDate().getTime()) //End: 1467580329936
console.log('Difference: ' + parseInt(begin - currentDate().getTime())) //Difference: -5414
clearInterval(interval);
}
I now have a variable called difference that contains the number of milliseconds between the start time and stop time.
When the user clicks "Resume", I need to get the current date and add the difference of milliseconds we got. That should then resume the timer from where they currently left off using the new point in time.
How can I go about adding the milliseconds to the current date in order to get the new starting point?
I tried something like this with no luck:
var mili = 4512;
var newDate = new Date(mili*1000);
UPDATE: here is a link to my timer code so you can see what I am working with.
https://jsfiddle.net/3dweffy8/3/
I got the timer to pause by clearing the interval but I am not sure how to continue with getting the timer to resume at this point.

Get the current timestamp using Date.now(), add the amount of milliseconds and make a new Date object from it:
var newDate = new Date(Date.now() + mili)

Write an Object to do the bookkeeping.
The object will carry the last timestamp and the measurements, either as a sum or as an array.
It exposes function start(), stop(), pause(), resume().
in start(): reset the measurements and get the current Date as referenceDate for your next measurement. If the tracker is already running, do nothing.
stop(): calculate the difference between current date and referenceDate. The counter is no longer active. Maybe archive the remaining results.
pause(): calculate the difference between current date and referenceDate. If you want to measure breaks, set referenceDate to current date.
resume(): If you measure breaks, calculate the difference between current date and referenceDate.
In any case, set referenceDate to current date.
Usage:
var tracker = new Tracker();
// start
tracker.start();
// Pause the timer
function pause(){
tracker.pause();
console.log('Begin : ' + tracker.startOfEvents); //Begin:1467580324524
console.log('End: ' + tracker.lastMeasurement); //End: 1467580329936
console.log('Difference: ' + tracker.difference) //Difference: -5414
// was this part of your measurement?
clearInterval(interval);
}
// later
tracker.resume();

Related

How can I shift in time an array of timestamps in javascript?

I have an array of time objects created like this:
let event = new Date()
These events are created overtime, for example:
first event created*
2 seconds later another event created
5 seconds later another event
3 seconds later another is created etc...
So each time object has the corresponding time at which it was created.
The events where obviously created in the past, and there is afirst event.
and they are all stored in an array like: [event1, event2, event3...]
The events are the object the function new Date() returns.
How can I shift all these events so that they start in the future?
By the future I mean for example whenever an event is executed, a click etc...
How can i shift their time equally to that all events go in the same order, but start in the future.
Is like a recording, being played back.
Thanks
While Date handling is one of the pretty bad parts of JS1, this short of shifting is relatively simple. We just calculate new timestamps based on the difference between the first date in the list and the current one, and add that difference to our new start time, then create a Date from that timestamp:
const shiftEvents = (start, events) =>
events .map (e => new Date (e - events[0] + start .getTime ()))
const events = [new Date ('2022-03-09T22:51:03.507'), new Date ('2022-03-09T22:51:05.492'), new Date ('2022-03-09T22:51:10.604'), new Date ('2022-03-09T22:51:13.551')]
console .log (shiftEvents (new Date ('2022-03-16T22:59:18.219'), events))
1 There is something better on the horizon in the Temporal proposal.
var events = [...];
var firstEvent = events[0];
var now = new Date();
var oldestEventAge = now.getTime() - firstEvent.getTime();
var hour = 1000 * 60 * 60;
for (let e of events) {
e.setTime(e.getTime() + oldestEventAge + hour);
}
Here we get the first event and calculate how many milliseconds have occurred between now and it. i.e. how old is it.
Then we define 1 hour in milliseconds. This is how far we are pushing the first event into the future.
Then for each event we add to its current time in milliseconds the age of the oldest event plus one hour.
This will result in the oldest event being 1 hour in the future and all subsequent events being the same distance from the oldest event and also in the future.
Obviously change the value of hour to be however far you want the first event to be in the future.

function reminding me about a date

I have a function and it represent a date that is 2 weeks off from start date, counted by each passing Thursday, but excludes the Thursday of the week the date was made.
function GetThursdayIn2Weeks(date)
{
var day = date.getDay();
// Add 2 weeks.
var newDate = new Date(date.setTime(date.getTime() + (14 * 86400000)));
// Adjust for Thursday.
var adjust = 4 - day;
if (adjust <= 0) // Might need to be changed - See comments!
adjust +=7;
// Apply Thursday adjustment.
newDate = new Date(newDate.setTime(newDate.getTime() + (adjust * 86400000)));
return newDate;
}
How would I make this set off a different function every day that passed, starting a week after the beginning of the process, remind me about the due date coming up, but before the end of the date of the process?
You can use setTimeout() to execute a reminder after a set time. However, the problem is that your javascript environment will probably not keep running for such long times, be it node.js or your browser.
I would suggest those mechanisms :
store your target date in localstorage after calculating it with your given code
define a function that will use setTimeout() to define the next occurrence of the reminder for a given target date
when the page is loaded, use that function for each date stored in the localstorage
when a date is added to the localstorage, or a given target date reachs one of its reminders, call the function for this specific date
The mentioned function should set a timer for the first day that is at the same time greater than the current date, greater than the day 1 week before the target date, and lower than the target date.
Here is an 'hopefully) working JSFiddle.

code in javascript that ask for start and end time for a particular behavior

i am making a Quiz app and i want a functionality that should start quiz based on start time and end time. for example quiz should start at 9:00 AM and should stop and 9:20 AM.
time should be provided by Admin
and after end time quiz should be submitted automatically.
Using JavaScript's Date().getTime() we can call for the current time in milliseconds (which is the number of milliseconds since midnight, 1 Jan 1970):
var curTime = new Date().getTime();
Now we calculate the amount of time in milliseconds we wish to timeout for:
20*60*1000 = 120000 milliseconds
(Twenty minutes)(seconds in minute)(milliseconds in a second)
You could also rewrite it as to adjust by minutes only:
var min = 20, var timeLimit = min*60000;
Then, set a timeout based on our current time and the time limit:
var timeout = curTime+timeLimit;
Finally we use this to compare the current time to and if it's past (greater than) the timeout we call a close function for the quiz and optionally display a message.
if(new Date().getTime() > timeout) {
alert("The quiz has expired");
}
The finished code looks a bit like this:
var curTime = new Date().getTime(), min = 20, var timeLimit = min*60000, timeout = curTime+timeLimit;
if(new Date().getTime() > timeout) {
alert("The quiz has expired");
}
From here you can derive any number of modifications. Say you want to set the the availability between two determined time periods. You would need a method of input that was human readable for the start and end time. So the conversion of dates and times to milliseconds would be necessary.
To store the date you will want a set of dropdown menus which can then store the chosen date for both start and end times. An example dropdown would look as shown:
<select id="quizStartHours">
<option value="1">1</option>
<option value="2">2</option>
<option value="3">3</option>
...
<option value="12">12</option>
</select>
You will want to make the above for each start and end for hours, minutes (increments of 5 suggested in this case), month, month day (limited by number of months varyingly, 28-31). If you wish to only quiz on same days not over a period of days you could simplify it into a single year & month for both start & finish - hours & minutes.
One project that may help you on date dropdown menus is ComboDate, which may also store input into the date() format for us to use with var curTime = new Date().getTime();.
Now we store the user input. To store it on a server, you'll have to get into ajax a bit and server side variables. I'm not too sure how that works at the moment, here is an inquiry regarding how to do so using vbscript to help you if you wish to do so. Hopefully someone more knowledgeable can assist if that's an issue.
For now, I'll continue with a focus on local variable storing for example purposes. Here is an example of how to record the user input from the hour dropdown:
var e = document.getElementById("quizStartHours");
var strUser = e.options[e.selectedIndex].value;
In order to use the input we must store it in milliseconds that will work with the curTime, date() does so out of the box:
var quizStartDate = new Date(quizStartYear, quizStartMonth, quizStartDay, quizStartHours, quizStartMinutes);
var quizEndDate = new Date(quizEndYear, quizEndMonth, quizEndDay, quizEndHours, quizEndMinutes);
You may learn more about how date() behaves here.
Now that we have our start and end dates we can now check for availability based on the current time (curTime) and our quizStartDate & quizEndDate variables:
var quizAvaliable = quizEndDate > curTime && curTime > quizStartDate;
The final code would look something like this:
// on quiz listing & opening check for curTime
var curTime = new Date().getTime(), quizAvaliable = quizEndDate > curTime && curTime > quizStartDate;
if(quizAvaliable) {
alert("The quiz is open");
//allow access to quiz itself (menu linking, page publicity)
}
else if(curTime > quizEndDate) {
alert("The quiz has expired");
//save then close quiz, in that order
}
else {
alert("The quiz has not begun");
}
Hopefully this helps with figuring out how to do all of this. Here I focused primarily on the separate steps of the process, and how to perform each. However this is client side, for security you may want to go server side, which is what Ajax (asynchronous JavaScript and XML) coding is for.
Best of luck!
Any items in bold should be looked up if you wish to learn more if you haven't already.

using setTimeout to execute function excatly at specified time

here is my code below..
setTimeout(executeQuery, 5000);
Iam aware that executeQuery will run after 5 second... but I want to run it exactly at e.getHours()+':'+e.getMinutes() where
console.log(e.getHours()+':'+e.getMinutes()); will display 1:30 ,Iam trying to run a a function today at 1:30 anyways to fix this???
Set the date and time when you want to run the function using new Date(year, month, day, hours, minutes, seconds, milliseconds); . Get the current new Date() , and substract the difference in their milliseconds count, assign it to the setTimeout function. See the following snippet:-
window.onload=function(){
var date1=new Date();
var date2=new Date(2014,05,27,11,45,00);
var diff=date2.getTime()-date1.getTime();
setTimeout(executeQuery, diff);
}
function executeQuery(){
alert("hello");
}
Fiddle
Pretty straight forward:
var today = new Date();
var target = new Date(today.getFullYear(), today.getMonth(), today.getDate(), 1, 30, 0);
var timeout = target.getTime() - new Date().getTime(); // today variable is slightly out of date by now, if that matters
setTimeout(executeQuery, timeout);
Basically you just get the milliseconds for today and your target date, then the difference is what you need to set your timeout to :).
EDIT: Keep in mind that 1:30 is 1:30am, meaning this code will have to execute before then to work. If it executes after that, it'll default to the minimum timeout delay (varies, but less than 10ms). A simple check to see if timeout is < 0 and if it is reset target to tomorrow. Eg:
if (timeout < 0) {
target = new Date(today.getFullYear(), today.getMonth(), today.getDate() + 1, 1, 30, 0);
timeout = target.getTime() - new Date().getTime();
}
EDIT2: Also, keep in mind the client's PC needs to stay on your website the entire time for this to work (assuming this is client side script). If you need to ensure something happens whenever somebody is looking at the page at that time, then this is fine, otherwise, it is not.
You have to take in mind the async processes are pseudo async, i.e. when one occurs (like click, a timer firing, or an XMLHttpRequest) it is queued until there is resource to execute it (this varies from browser-to-browser). Because there is no actual threading setTimeout (in your case) is queued to be executed in next possible moment. When it occurs depends on the source code.
A good reading on the topic you could find here
setInterval(function(){
var d = new Date();
if (d.getSeconds()==0) {
if (d.getMinutes()==30) {
if (d.getHours()==1) {
alert("Hello")
}
}
}
}, 1000);

Trouble with .getTime()

I am fairly new to HTML and Javascript, so I'm trying to make a small incremental game as practice. This is the code I am trying to use to calculate the automatic gains / second, as well as adjust accordingly for when the tab isn't in focus and setInterval stops running.
var startTime = new Date();
var endTime = new Date();
var interval = 100;
window.setInterval(function(){
startTime.getTime();
var timeDiff = startTime - endTime;
do{
document.getElementById('woodAmount').innerHTML = Math.floor(user.wood += (user.WPS/10));
document.getElementById('oilAmount').innerHTML = Math.floor(user.oil += (user.OPS/10));
document.getElementById('goldAmount').innerHTML = Math.floor(user.gold += (user.GPS/10));
document.getElementById('coalAmount').innerHTML = Math.floor(user.coal += (user.CPS/10));
timeDiff -= interval;
}while (timeDiff >= interval);
endTime.getTime();
}, interval);
For some reason, this code doesn't adjust for the time when the tab is not focused, but it works as expected when it is in focus.
As you can see here, I set the interval to 100 milliseconds, and I divide the resources / second (user.WPS) by 10.
However, when I set the interval to 1 second (1000 milliseconds) and don't divide the resources / second by 10, it works as expected all the time, and properly adjusts for the time that the tab isn't focused.
Can anyone offer an explanation as to why it works when using full-second intervals, but won't when using 100 millisecond intervals?
.getTime() gets the time that is already in the Date object at the time it was created or whenever the time was last set in the date object. It does NOT get the current time.
If you want to get the current time, I often use this little function:
function now() {
return new Date().getTime();
}
Or, if you don't need IE8 support, then you can use Date.now().
In addition, the getTime() method pulls the time out of the data object and returns it from that method call. If you want to use it, you have to put it somewhere after calling .getTime().

Categories