Open Modal in a specific date/time [duplicate] - javascript

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

Related

How to Refresh page at particular time [duplicate]

This question already has answers here:
How to automatically reload a web page at a certain time?
(10 answers)
Closed 7 years ago.
I am using javascript to refresh my page at 5:25 pm EST.
For example if a user come to my page at 5.00pm EST and he stay at 5.40pm EST let suppose.Then I want to refresh my page at 5.25pm EST.
how can I achieve this?
Use setInterval to check time at specific intervals and if desired time is reached, just use location.reload:
window.setInterval(funciton() {
var now = new Date();
if(now.getTime() == SOMETHING) {
location.reload();
}
}, REFRESH_INTERVAL);
If you want to use time zone calculation, etc. I suggest moment.js.
UPDATE:
There is a nice snippet provided in this answer, which does it more elegantly.
You can compute time to reload and then set timeout function to reload page:
var now = new Date()
var timeOfRefresh = new Date();
timeOfRefresh.setHours(5);
timeOfRefresh.setMinutes(25);
timeOfRefresh.setSeconds(0);
var diff = timeOfRefresh.getTime() - now.getTime();
if (diff < 0) { // is after 5:25
diff += 24 * 60 * 60 * 1000; // refresh next day
}
setTimeout(location.reaload, diff);

javascript - time counter since start date and time

I have a new business, where I just hired someone to work for me, I am trying to make it easy for her to track her time, so I created a clock in button, that creates a record in a database, I have it pop up a small window, that she can click to clockout when she is done working.
I want it to show her on that popup window a counter that will show how long she has been working, so I want to create a javascript or jQuery that will start at a certain time and count from there. She is on the East Coast, our company is in the Central Timezone, so 1 hour behind her.
How can I get a javascript to start from a certain time and keep updating the timer, so she can see something like this:
[You've been working for: 01:01:01 HH::MM::SS] - and it is actively updating, climbing up.
All the timers I've found are not about time itself, but about starting at a time and counting down, or starting at 0 and counting up.
Is there a way to tell it a start time, so that way if she reloads the page, it does not start from 0, but will start at the time she clocked in, then add the time since and start from there?
I know it can be done, but I'm more of a Perl guy than a Javascript guy. I'm doing this on Wordpress, so I could use PHP and just tell her to refresh the page to see the current amount of time and then have it on page load show the current amount of time, but I think having a counter would be better and make it easier for her.
is there some code already done that I could modify myself to make it work? I cannot find any, anywhere. I'm willing to do all the work, I'm not asking for someone to do it for me.
I found this example someone did:
function get_uptime() {
var t1 = new Date()
var t2 = new Date()
var dif = t1.getTime() - t2.getTime()
seconds = dif / 1000;
Seconds_Between_Dates = Math.abs(seconds);
document.getElementById("seconds").innerHTML = Seconds_Between_Dates;
setTimeout(get_uptime, 1000);
}
get_uptime();
That is sort of it, but I don't now how to put the first time in t1, what format do I put it in?
I can have PHP put it in any format, but not sure the one it needs.
Plus this appears to only put the seconds, not hours, minutes and seconds.
Is there away to do that?
Thanks,
Richard
From your question I understand you store the date and time on start?
So then you can use PHP to echo this information in a starting Date object and let a setInterval-function do the current timegetting and calculation of the time working.
See working example here: http://jsfiddle.net/c0rxkhyz/1/
This is the code:
var startDateTime = new Date(2014,0,1,23,59,59,0); // YYYY (M-1) D H m s ms (start time and date from DB)
var startStamp = startDateTime.getTime();
var newDate = new Date();
var newStamp = newDate.getTime();
var timer; // for storing the interval (to stop or pause later if needed)
function updateClock() {
newDate = new Date();
newStamp = newDate.getTime();
var diff = Math.round((newStamp-startStamp)/1000);
var d = Math.floor(diff/(24*60*60)); /* though I hope she won't be working for consecutive days :) */
diff = diff-(d*24*60*60);
var h = Math.floor(diff/(60*60));
diff = diff-(h*60*60);
var m = Math.floor(diff/(60));
diff = diff-(m*60);
var s = diff;
document.getElementById("time-elapsed").innerHTML = d+" day(s), "+h+" hour(s), "+m+" minute(s), "+s+" second(s) working";
}
timer = setInterval(updateClock, 1000);
<div id="time-elapsed"></div>
Attention! The month number in the new Date() declaration is minus one (so January is 0, Feb 1, etc)!
I would use momentJS fromNow function.
You can get the time started as variable on page load then call fromNow on that and current time to get time between the two every time the clock is clicked:
var StartedWorkDateTime = GetStartedTime();
moment(StartedWorkDateTime).fromNow(true);
Non momentJS:
var date1 = new Date("7/11/2010 15:00");
var date2 = new Date("7/11/2010 18:00");
var timeDiff = Math.abs(date2.getTime() - date1.getTime());
var diffHours = Math.ceil(timeDiff / (1000 * 3600));
alert(diffHours);
reference
Get the difference between two dates by subtracting them:
var duration = end - start;
This will give you the number of milliseconds between the dates. You can use the milliseconds to figure out hours, minutes, and seconds. Then it's just a matter of string manipulation and writing the value to the page. To update the timer once per second, use setInterval():
setInterval(writeDuration, 1000);

Run JS function every new minute

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.

Do something at a specific time of the day js

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

How to find the remaining time of a setTimeout() [duplicate]

This question already has answers here:
Closed 12 years ago.
Possible Duplicate:
Javascript: find the time left in a setTimeout()?
I'm trying to use setTimeout() as a way of pausing a series of events in JS.
Here's an example of what I'm doing and what I'd like to do in comments - http://jsfiddle.net/8m5Ww/2/
Any suggestions how I can populate var timeRemaining with the total milliseconds remaining in var a?
You can't get directly the timer remaining seconds.
You can save in a variable the timestamp when the timer is created and use it to calculate the time to the next execution.
Sample:
var startTimeMS = 0; // EPOCH Time of event count started
var timerId; // Current timer handler
var timerStep=5000; // Time beetwen calls
// This function starts the timer
function startTimer(){
startTimeMS = (new Date()).getTime();
timerId = setTimeout("eventRaised",timerStep);
}
// This function raises the event when the time has reached and
// Starts a new timer to execute the opeartio again in the defined time
function eventRaised(){
alert('WOP EVENT RAISED!');
clearTimer(timerId); // clear timer
startTimer(); // do again
}
// Gets the number of ms remaining to execute the eventRaised Function
function getRemainingTime(){
return timerStep - ( (new Date()).getTime() - startTimeMS );
}
This is custom sample code created "on the fly".
Not possible, but if you set the contents of a separate var to the time you set it, you can easily figure it out manually.

Categories

Resources