How can i fire a function at a specific time and date. eg: 8:30 every Wednesday. The solution that i can think of is checking time with an interval but loops are laggy especially when you have to check every minute. Are there any alternative solution. Please help, thanks.
Something like...
var dateItHappens = new Date()
// ... set the dateItHappens variable up ...
var millisTillOccurence = dateItHappens.getTime() - new Date().getTime();
setTimeout(function(){ /* ... function you want to call ... */ }, millisTillOccurence);
if you are using node you can use node-cron package,
and
cron.schedule('* * * * * *',async()=>{
// your task
)
first star represent seconds, next minute and so on........
Related
I'm fairly new to javascript and programming at all, to be honest. I know html and css and the basics of javascript and I'm trying to figure out how time works in js.
I would like to make a simple game where the user can take care of a horse. And every action he does (i.e brushing the mane) would take a specific amount of time. Let's say five minutes for that. How do I code that?
Would be really thankful if anyone could tell me. Thank you in advance.
Jolly
just get the time in the future when the even would be finished at.
use this function
function getTime(numOfHours) {
let date = new Date();
date.setTime(date.getTime() + numOfHours * 60 * 60 * 1000);
return date;
}
then do check in your game logic to see if the event end time against the current time.
let endEventTime = getTime(0,00138); // add 5 seconds to the current time
// do a loop or some setTimeout() login and once the time passes then let your user do another action.
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.
This question already has answers here:
Call a javascript function at a specific time of day
(4 answers)
Closed 9 years ago.
I've been developing a web app, and I was wondering if there is a way to display a model at a specific date/time.
In the app, the user can book task or reminders, so when I read from the database the task a specific I want to schedule the display of the modal at the date/time specify by the user.
For instance, the user book a task for 2013-09-23 at 14:00 and I want to display a message in the modal.
I kwon we can set time interval with the JavaScript:
setInterval(function () {
showModal();
}, 10 * 1000);
But how to specify an hour like in the sample?
In that setInterval call, 10 * 1000 means 10 times 1000 milliseconds, or in other words 10 seconds. If you want an hour, it's just a bigger number. 1000 * 60 * 60 is an hour.
However, setInterval is for running a function multiple times. Unless you wanted it to be called every hour, you are probably looking for setTimeout instead. setTimeout schedules a function to be run once after the time period expires.
You can try like this.
Make your setInterval() to run for a continues time.
Compare the date, by converting them to milliseconds. and a comparison condition.
setInterval(function () {
var date = new Date("2013-09-23 14:00");
var schDateSecs = Date.parse(date);
var currentDate = new Date();
var schCurrentSecs = Date.parse(currentDate);
if (schDateSecs == schCurrentSecs) {
//execute
showModal();
}
}, 10 * 1000);
Thank you all for your answers, they help me come up with a solution:
function setNotification(notificationDate, notificationCallback){
var currentDate = new Date();
var date = new Date(notificationDate);
var interval = date - currentDate;
if(interval > 0)
window.setTimeout(function(){ notificationCallback(item)}, interval); //notificationCallback = showModal()
}