I need to create a special kind of script.
I want to show a message at certain times of the day. I've tested the code in Firebug Console and it works. The code is:
//Getting the hour minute and seconds of current time
var nowHours = new Date().getHours() + '';
var nowMinutes = new Date().getMinutes() + '';
var nowSeconds = new Date().getSeconds() + '';
var this_event = nowHours + nowMinutes + nowSeconds;
//172735 = 4PM 25 Minutes 30 Seconds. Just checked if now is the time
if (this_event == "162530") {
window.alert("Its Time!");
}
I feel that the Script is not running every second. For this to work effectively, the script has to be able to check the hour minutes and second "Every Second". I'm not worried about the performance, I just have to be accurate about the timing (to the second).
How do I do this?
Of course the script isn't running each second, GM-scripts run once when the document has been loaded.
Calculate the difference between the current time and the target-time and use a timeout based on the difference:
var now=new Date(),
then=new Date(),
diff;
then.setHours(16);
then.setMinutes(15);
then.setSeconds(30);
diff=then.getTime()-now.getTime();
//when time already has been reached
if(diff<=0){
window.alert('you\'re late');
}
//start a timer
else{
window.setTimeout(function(){window.alert('it\'s time');},diff);
}
Javascript doesn't guarantee your timeouts and other such events fire exactly on-time.
You should compare two Date objects using >= and remove the timeout or what ever other method you're using for tracking the time inside the matching if (and then reset it if necessary).
For more details see: https://stackoverflow.com/a/19252674/1470607
Alternatively you can use string comparison (but with caveats): https://stackoverflow.com/a/6212411/1470607
Related
I realized that a change in system time is not immediately reflected in javascript, event if I use a new Date object. It is only updated every minute.
var fakeElapsed = 0;
$(document).ready(function(){
var oldTime = 0;
function fakeTimeLoop(time){
fakeElapsed+=(time-oldTime);
oldTime = time;
$("div").html(fakeElapsed);
}
var clock = new Date();
var start = clock.getTime();
oldTime = clock.getTime();
setInterval(function(){
var clock2 = new Date();
var end = clock2.getTime();
var elapsed = end-start;
if(elapsed%5===0){
fakeTimeLoop(end);
}},
1
);
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<body>
<div></div>
</body>
Time code, if you would turn time forward (or backwards), it takes a minute to change the time elapsed.
Is there anyway to update to the system time every second?
Edit: for those who are confused, a change in system is not reflected immediately on Chrome and Opera, but on IE and Mozzila, it is immediately reflected, I assume its order to avoid expensive system calls every time it needs to build a new Date object.
What I am looking for: is that anyway to get the current system time in chrome/opera or detect a change in system time immediately?
It's not exactly clear to me what you're trying to accomplish, but your setInterval is programmed to execute every millisecond (the second parameter is in milliseconds), but browsers treat any value less than 10 as equal to 10. Even with that restriction, the timing isn't guaranteed to be exact, so the function may well execute every 11, 12, 13, etc. milliseconds.
When you change your computer date/time and refresh the web page, new Date() will not return correct date/time. After 20-25 seconds it will return correct time. Probably it is a browsers' bug (I tested on Windows 10, Edge an Chrome).
I want to reset a variable during midnight. Every night.
I'm trying to build this function with Moment.js for Node but I can't seem to get the recurring part to work properly.
This is what I got so far.
// Calculate time to midnight
function timeToMidnight(){
var midnight = new Date();
midnight.setHours(0,0,0,0);
var now = new Date();
var msToMidnight = midnight - now;
console.log(' it is ' + msToMidnight + 'ms until midnight');
return msToMidnight;
};
// Reset counter at midnight
setTimeout(function(){
console.log("midnight, do something");
}, timeToMidnight());
How can I best make it recurring at midnight, every night?
Thanks in advance.
If you're using moment, consider instead this implementation
var moment = require('moment');
function timeToMidnight() {
var now = new Date();
var end = moment().endOf("day");
return end - now + 1000;
}
Like your function, this takes now milliseconds and calculates the number of milliseconds until midnight, but this is supported directly when using moment, which is nice. Add 1 extra second (1000 milliseconds) to get to the next day.
A typical pattern is for a function to call itself after a timeout.
function roundMidnight() {
console.log('at midnight');
setTimeout(roundMidnight,timeToMidnight());
}
setTimeout(roundMidnight,timeToMidnight());
Pretty generic, in fact depending on the value returned, you could schedule anything anytime, pretty useful, seem like someone must have thought of that.
node-schedule
A cron-like and not-cron-like job scheduler for Node.
And they did. Maybe what you really want is node-schedule. It looks like it's not really actively developed now, though.
I'm pretty new to JavaScript so please keep that in mind when answering my question.
I'm trying to make something where it asks the user questions during a certain time frame. Questions are asked using the window.prompt() method. I have a do while loop going on in a function called askquestions() as you can see:
var randomNo1;
var randomNo2;
var time;
do {
randomNo1 = Math.random() * 9;
randomNo1 = Math.round(randomNo1);
randomNo2 = Math.random() * 9;
randomNo2 = Math.round(randomNo2);
window.prompt("What is " + randomNo1 + " + " + randomNo2 + "?")
} while (time == 0);
How can I make it that time = 1 after 30 seconds?
Thanks in advance for your help.
You can use:
document.setTimeout("str js code/func name call",millisec);
document.setTimeout("time=1;",30000);
to execute some js code once with delay
And for your specification the following method may be needed for other timing purposes:
document.setInterval("js code /func name call",millisec);
to execute at an interval
Besides,it is strongly not recommended to have a "waiting while" in your js code to provide some timing service, which may cause browser to take this thread as a not-responding thread
You could get the milliseconds since Jan 1 1970 using
date = new Date();
mil = date.getTime();
You do that at the beginning of your code for comparison, then get a more current one in the loop. If the time between the two is greater than some number of milliseconds, you can exit the loop (while(curDate.getTime()-mil<30000) would be 30 seconds)
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.
I have a scenario where one client PC will be driving multiple LCD displays, each showing a single browser window. These browser windows show different data which is on an animated cycle, using jquery.
I need to ensure that both browsers can be synched to rotate at exactly the same time, otherwise they'll animate at different times.
So my question is - can I trigger jquery to alternate the content based on the local PC clock?
eg each time the clock seconds == 0, show version 1, each time clock seconds == 30, show version 2 etc?
This is (in my experience) the most precise way of getting timers to trigger as closely as possible to a clock time:
// get current time in msecs to nearest 30 seconds
var msecs = new Date().getTime() % 30000;
// wait until the timeout
setTimeout(callback, 30000 - msecs);
Then, in the callback, once everything is done, do the same again to trigger the next event.
Using setInterval causes other problems, including clock drift. The calculation based on the current time accounts for the time executing the callback itself.
You'll still also need to use Date().getTime() as well to figure out which frame of your animation to show.
The whole thing would look something like this:
function redraw() {
var interval = 30000;
// work out current frame number
var now = new Date().getTime();
var frame = Math.floor(now / interval) % 2; // 0 or 1
// do your stuff here
.. some time passes
// retrigger
now = new Date().getTime();
setTimeout(redraw, interval - (now % interval));
}
redraw();
working demo at http://jsfiddle.net/alnitak/JPu4R/
The answer is: yes you can.
Use Date.getTime() to monitor time
Trigger your js function every 30 seconds
You could do something like this.
This way, no matter when you launched the different browsers, their rotations would be in sync.
var t=setInterval("check()",1000);
function check(){
var d = new Date();
if(d.getSeconds() == 0)
{
alert('do something');
} else if (d.getSeconds() == 30)
{
alert('do something else');
}
}
Why not launch one window from the other - that way the parent window will have complete control over when the animation starts, because they are in the SAME PROCESS. No clocks required.