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().
Related
I am trying to display sort of a "time since" counter on my website. The API call outputs like this.
"created_at": "2018-05-16T14:00:00Z",
How would I go toward displaying the time since this time? This time is always set UTC time zone.
Preferably in a hh:mm format.
Appreciate all help.
This is very simple
var create_at = new Date("2018-05-16T14:00:00Z");
var current_time = new Date();
var elapsed_time = current_time - create_at;
elapsed_time is the time since create time in milliseconds. You can get seconds dividing it by 1000 like this.
var elapsed_seconds = elapsed_time / 1000;
I am creating a countdown on a session that is 20 minutes. When I do a get request I get back
20.
This is fine. My next step is to set this so that it can be subtracted by
1000 milliseconds on an $interval
I have tried the following code
var d = moment.duration(x, 'milliseconds');
moment(d.asMinutes(),'mm').format('mm:ss');
Which returns
"21:00"
This is great, but the problem is now I have a string. I am not sure how I can start subtracting seconds off of this timer.
Any help would be greatly appreciated.
If you just want a session timeout there's no need to complicate things, use setTimeout:
const SESSION_MAX = 20 * 60 * 1000; // 20 min to milliseconds
setTimeout(logOutFunction, SESSION_MAX);
If for some reason you want more control, then just work with the integers returned by a Date object's native getTime:
let start = Date.now();
let end = start + (20 * 60 * 1000);
const INTERVAL = 1000; //ms
Then increment start on a clocktick and check if its >= end.
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();
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);
I have a field in my database which states the timezone of the user. It is an integer field so anything > 0 is a + hour.
I need to display two separate times on the users screen
e.g.
Your time is: "just get the current computer time"
The other users time is: "get the current computer time then either add or subtract hours based on the database record"
I can do the database side of things I just need help with the Javascript element. For demonstration purposes I am happy for you to hard code the offset
The time must update automatically every 60 seconds to reflect the new minute and hour
Thanks
You can just set the hours on the date object in JavaScript. For example:
var date = new Date();
date.setHours((new Date()).getHours() - 5);
It will also try and be clever and make adjustments for you, as MDN says:
If a parameter you specify is outside of the expected range, setHours
attempts to update the date information in the Date object
accordingly. For example, if you use 100 for secondsValue, the minutes
will be incremented by 1 (min + 1), and 40 will be used for seconds.
You can use setInterval to perform the update. Here's a more complete example:
setInterval(function() {
var local = new Date();
var remote = new Date();
remote.setHours(local.getHours() - 5);
$('#time-local').html(local.toGMTString());
$('#time-ny').html(remote.toGMTString());
},1000);