using setTimeout to execute function excatly at specified time - javascript

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);

Related

Is there any way where i can define maximum duration to execute any schedule script?

IE. I implement schedule script, which contain block of statements to execute, now i need to define that the execution process need to complete within a 1:30 minute. after 1:30 minute execution should be stop and give message.
There's currently no timeout method in Netsuite for serverside scripts. What you can do is set up a variable that holds the end time and check on it from time to time like. Something like this:
var maxExecutionTime = 90; //In Seconds
var endTime = new Date();
endTime.setSeconds(endTime.getSeconds() + maxExecutionTime);
if(new Date() > endTime){
//exit
}

Javascript date + milliseconds

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();

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().

js - Fire event on midnight

I am making a simple web app using javaScript. At one part I want an event to fire when the date changes (i.e., 4th Jan becomes 5th Jan).
This is what I am doing:
window.onload=function(){
var today = new Date();
var tommorow = new Date(today.getFullYear(),today.getMonth(),today.getDate()+1);
var timeToMidnight = (tommorow-today)/60;
var timer = setTimeout(function(){console.log("this");},timeToMidnight);
}
Anyhow, the problem I am facing is that the function is getting executed around 30-40 seconds before it is actually midnight. What's wrong? What should I do?
When you convert dates to numbers, you get milliseconds (see Date.prototype.valueOf).
That's the unit required by setTimeout. So you don't have to divide.
Change
var timeToMidnight = (tommorow-today)/60;
to
var timeToMidnight = (tommorow-today);

setTimeout but for a given time

Is there anything readily available in JavaScript (i.e. not through "plugins") that allows me to do something like setTimeout, but instead of saying in how many milliseconds something should happen, I give it a date object telling it when to do something?
setToHappen(function () {
alert('Wake up!');
}, new Date("..."));
And yes, I know I can do this by simply subtracting new Date() with my existing date object (or maybe it's the other way around) to get the amount of milliseconds, but I'd still like to know.
You have to compute the number of milliseconds between now and your date object:
function setToHappen(fn, date){
return setTimeout(fn, date - Date.now());
}
NB Please note #calvin's answer: this will not work if the number of milliseconds is greater than 2147483647.
Since people are talking about calculating timeout intervals using date objects, it should be noted that the max value setTimeout() will accept for the interval parameter is 2147483647 (2^31 - 1) as PRIntervalTime is a signed 32-bit integer. That comes out to just under 25 days.
No, but you could easily write your own function. Just calculate the diference between now and the given moment in miliseconds and call setTimeout with that.
Something like this:
setToHappen = function(fn, date){
var now = new Date().getTime();
var diff = date.getTime() - now;
return setTimeout(fn, diff);
}
EDIT: removed the extra multiplication by 1000, thanks chris for pointing that out!
You can simply subtract Date.now() from the date
const myDate = new Date('...');
setTimeout(func, myDate - Date.now());

Categories