Timer - Count up timer for Angular 8 - javascript

I am trying to display a timer as shown below in this screenshot. To count up constantly to show how long since this entry has been made.
I couldn't find too many options for doing it in Angular. I found this solution in Angular JS. https://siddii.github.io/angular-timer/ I need the timer exactly like this. But I was not able to port it into Angular or I couldn't. So tried the other alternatives available and found these still they are all also not working.
https://www.npmjs.com/package/ng2-simple-timer
https://www.npmjs.com/package/ngx-timer
The closest I got to was this ngx-timer's Countup-timer. https://www.npmjs.com/package/ngx-timer the timer works fine and its able to start from a given date as per my requirement. startTimer(startDate). But it has an known issue which is still unresolved that is it applies itself to the last known index of the timer element thereby only one timer running in a whole list of timers.You can notice that in the above given screenshot itself.
its a known bug. https://github.com/Y4SHVINE/ngx-timer-lib/issues
So can somebody help me with a solution or some tweaks to one of these solutions to make it work.
Thanks.

I would do this by writing a function to return the difference between the current time and the creation time of an object.
My initial thought was to return the difference as a Date object and then format the result. I soon ran into problems when formatting different time spans, as a date is not the same thing as a time span.
So instead of trying to format a Date that is pretending to be a time span, I would create my own interface.
export interface TimeSpan {
hours: number;
minutes: number;
seconds: number;
}
By doing this we retain control of how time spans >= 1 day are handled, and avoid time zone issues.
I would use OnPush change detection to keep control over when change detection is run:
#Component({
selector: 'my-app',
templateUrl: './app.component.html',
changeDetection: ChangeDetectionStrategy.OnPush
})
export class AppComponent {
constructor(private changeDetector: ChangeDetectorRef) {}
}
I would then kick off an RxJS interval in ngOnInit(), making sure to unsubscribe when we're finished:
private destroyed$ = new Subject();
ngOnInit() {
interval(1000).subscribe(() => {
this.changeDetector.detectChanges();
});
}
ngOnDestroy() {
this.destroyed$.next();
this.destroyed$.complete();
}
The HTML would then get the elapsed time from a function on my component:
getElapsedTime(entry: Entry): TimeSpan {
let totalSeconds = Math.floor((new Date().getTime() - entry.created.getTime()) / 1000);
let hours = 0;
let minutes = 0;
let seconds = 0;
if (totalSeconds >= 3600) {
hours = Math.floor(totalSeconds / 3600);
totalSeconds -= 3600 * hours;
}
if (totalSeconds >= 60) {
minutes = Math.floor(totalSeconds / 60);
totalSeconds -= 60 * minutes;
}
seconds = totalSeconds;
return {
hours: hours,
minutes: minutes,
seconds: seconds
};
}
This function starts off by getting the total number of seconds elapsed since the creation date, and then works out the hour, minute, and second components.
Where entry is the object that contains some Date instance indicating its creation time. For my demo, I am using this interface:
export interface Entry {
created: Date;
id: string;
}
The elapsed time span can then be retrieved for each instance inside an *ngFor like this:
<span *ngIf="getElapsedTime(entry) as elapsed">
{{elapsed.hours}} h {{elapsed.minutes}} m {{elapsed.seconds}} s
</span>
DEMO: https://stackblitz.com/edit/angular-p1b9af

You could do this with RxJS like this:
const startDate = new Date('2020-03-08 14:12:23');
timer(1000, 1000)
.pipe(
map((x: number) => {
const newDate = new Date(startDate.getTime());
newDate.setSeconds(newDate.getSeconds() + x);
return newDate;
})
)
.subscribe(t => this.myDate = t);
Then in your component you do:
<div>{{ mydate | date: "hh 'h' mm 'm' ss 's'" }}</div>

Related

postman: How to add minutes to a dateTime while looping with JS?

I am trying to add 15 mins to a dateTime(2100-01-04T08:00:00) while looping.
For each run I want to add 15 minutes , so it would be 2100-01-04T08:15:00 , 2100-01-04T08:30:00 and so on…
I know I can do the below:
var moment = require('moment');
moment().add(15, 'minutes').toISOString();
But this will add 15 minutes to the current moment time but I want to add 15 minutes to 2100-01-04T08:00:00.
Is this possible in postman?
You can easily create an addMinutes() function to add a number of minutes to a date, you can then use a while loop to loop until a specified end date is reached.
In the example below, we'll add 15 minutes to the date until the end date is reached.
function addMinutes(date, minutes) {
let newDate = new Date(date);
newDate.setMinutes(newDate.getMinutes() + minutes);
return newDate;
}
let date = new Date('2100-01-04T08:00:00');
let endDate = new Date('2100-01-04T09:00:00');
let deltaMinutes = 15;
while (date <= endDate) {
console.log(date.toLocaleString('en-US'));
date = addMinutes(date, 15);
}
.as-console-wrapper { max-height: 100% !important; }
You can achieve this without using any third party libraries like momentJs.
The default javascript Date object has methods for getting the minutes property for a date object - getMinutes() and also another method for updating this minutes property - setMinutes().
Combining them both, you can achieve your required answer.
let x = new Date('2100-01-04T08:00:00')
for(let i = 0 ; i < 5; i ++){
x.setMinutes(x.getMinutes()+15);
console.log(x)
}
P.S, remove 'postman' from your question. It has nothing to do with the problem you are facing.

How to make requests using rxjs at the certain time?

I need to make request three times a day at a certain time (8 AM, 12 AM, 4 PM).
What is the best way to implement this?
This feels a bit like a strange requirement for a JS task and I think you should rather look into making a Cron task for that. But for the sake of example, here's how you can do it:
import { of, Observable, timer, EMPTY } from "rxjs";
import { map, filter, timestamp, switchMap } from "rxjs/operators";
type Hour = number;
type Minutes = number;
const atTimes = (times: [Hour, Minutes][]): Observable<[Hour, Minutes]> =>
timer(0, 1000 * 60).pipe(
switchMap(() => {
const date: Date = new Date();
const [currentHour, currentMinutes] = [
date.getHours(),
date.getMinutes()
];
const time = times.find(
([hour, minutes]) => hour === currentHour && minutes === currentMinutes
);
if (!time) {
return EMPTY;
}
return of(time);
})
);
atTimes([[11,48]]).subscribe(x => console.log(x));
Live demo: https://stackblitz.com/edit/rxjs-sxxe41
PS: I've assumed that the update doesn't need to be triggered as soon as the new minute starts. If that's the case, then timer should tick every second and you should use distinctUntilChanged on the current hour/minutes to wait until they're differents.
You should look into asyncScheduler from RxJS which uses setInterval for time based operations.
Refer to this link: https://rxjs-dev.firebaseapp.com/guide/scheduler
Ideally cron jobs are best on the server side to deal with functions need executing at different times, might be worth looking in that as well.

A repeating countdown timer that continues even after browser refresh

Firstly I am very new to javascript. I have a Shopify store and I am planning to have a countdown timer just like Amazon to each of my product pages. I know there are a lot of plugins I can use for Shopify but none of them matches with the theme and style of my Shopify store so I planned to make one myself.
What I want is if User-1 opens my website and navigates to a product page, he should see a timer counting down to a specific time say 12:00:00 (hh:mm:ss). Suppose User-1 sees 'Deal ends in 11:20:10' Now if User-2 opens the same product page at the same time then he should also see 'Deal ends in 11:20:10' The whole point is the timer should not refresh back to 12:00:00 every time the browser loads/reloads the page and every user on the website should see the same time remaining on the countdown timer.
I starting with a bit of research and managed to run a timer on my store. It's not exactly what I want but here's the code:
var interval;
var minutes = 1;
var seconds = 5;
window.onload = function() {
countdown('countdown');
}
function countdown(element) {
interval = setInterval(function() {
var el = document.getElementById(element);
if(seconds == 0) {
if(minutes == 0) {
el.innerHTML = "countdown's over!";
clearInterval(interval);
return;
} else {
minutes--;
seconds = 60;
}
}
if(minutes > 0) {
var minute_text = minutes + (minutes > 1 ? ' minutes' : ' minute');
} else {
var minute_text = '';
}
var second_text = seconds > 1 ? 'seconds' : 'second';
el.innerHTML = minute_text + ' ' + seconds + ' ' + second_text + ' remaining';
seconds--;
}, 1000);
}
</script>
And here's what it looks like:
It does work but has the following problems:
It refreshes with the browser refresh.
It doesn't have hours.
It does not auto-repeat when the timer reaches zero.
For every user time remaining varies.
As I mentioned I am almost a noob in JavaScript. Can anyone help me build a countdown timer that overcomes the above issues?
Explanation
Problem 1: It refreshes with the browser refresh.
Cause: Because you hardcoded the seconds and minutes (var seconds = 5, var minutes = 1), every user that visits the page will see the timer counting down from the exact same value being "1 minute and 5 seconds remaining" again and again.
Solution: Instead of hardcoding the start value of the countdown, hardcode the deadline. So instead of saying to each visitor of your page "Start counting down from 1 min and 5 sec to 0!", you have to say something like "Count down from whatever time it is now to midnight!". This way, the countdown will always be synced across different users of your website (assuming that their computer clock is set correctly).
Problem 2: It doesn't have hours.
Cause: Your code has only variables to keep track of seconds and minutes, there is no code written to keep track of the hours.
Solution: Like proposed in the solution for problem 1: don't keep track of the hours/minutes/seconds remaining, but only keep track of the deadline and then calculate hours/minutes/seconds remaining based on the current client time.
Problem 3: It does not auto-repeat when the timer reaches zero.
Cause: The nested ifs (that check seconds == 0 and m == 0) in your code explicitly state to display the text "countdown's over!" when the countdown is over.
Solution: Keep a conditional that checks when the countdown is over but instead of displaying "countdown's over!", reset the deadline to a next deadline.
Problem 4: For every user time remaining varies.
Cause: See Problem 1
Solution: See Problem 1
Sample code
here is a piece of code that integrates the solutions mentioned above:
const span = document.getElementById('countdown')
const deadline = new Date
deadline.setHours(0)
deadline.setMinutes(0)
deadline.setSeconds(0)
function displayRemainingTime() {
if (deadline < new Date) deadline.setDate(deadline.getDate() + 1)
const remainingTime = deadline - new Date
const extract = (maximum, factor) => Math.floor((remainingTime % maximum) / factor)
const seconds = extract( 60000, 1000 )
const minutes = extract( 3600000, 60000 )
const hours = extract(86400000, 3600000)
const string = `${hours} hours ${minutes} minutes ${seconds} seconds remaining`
span.innerText = `${hours} hours ${minutes} minutes ${seconds} seconds remaining`
}
window.setInterval(displayRemainingTime, 1000)
displayRemainingTime()
<h3>
<span id="countdown"></span>
</h3>
Edit: make sure the client time is correct
If you don't trust your clients for having their time set up correctly. You can also send a correct timestamp from the server that serves your page. Since I don't know what kind of server you are using I can't give an example for your server code. But basically you need to replace the code (from the following example) after const trustedTimestamp = (being (new Date).getTime()) with a correct timestamp that you generate on the server. For the correct formatting of this timestamp refer to Date.prototype.getTime()
const span = document.getElementById('countdown')
const trustedTimestamp = (new Date).getTime()
let timeDrift = trustedTimestamp - (new Date)
const now = () => new Date(timeDrift + (new Date).getTime())
const deadline = now()
deadline.setHours(0)
deadline.setMinutes(0)
deadline.setSeconds(0)
function displayRemainingTime() {
if (deadline < now()) deadline.setDate(deadline.getDate() + 1)
const remainingTime = deadline - now()
const extract = (maximum, factor) => Math.floor((remainingTime % maximum) / factor)
const seconds = extract( 60000, 1000 )
const minutes = extract( 3600000, 60000 )
const hours = extract(86400000, 3600000)
span.innerText = `${hours} hours ${minutes} minutes ${seconds} seconds remaining`
}
window.setInterval(displayRemainingTime, 1000)
displayRemainingTime()
<h3>
<span id="countdown"></span>
</h3>
Time from google server
To create a working example I added this experiment where I get the correct time from a Google page. Do not use this code on your website because it is not guaranteed that google will keep hosting this web-page forever.
const span = document.getElementById('countdown')
const trustedTimestamp = (new Date).getTime()
let timeDrift = 0
const now = () => new Date(timeDrift + (new Date).getTime())
const deadline = now()
deadline.setHours(0)
deadline.setMinutes(0)
deadline.setSeconds(0)
window.setInterval(displayRemainingTime, 1000)
window.setInterval(syncClock, 3000)
displayRemainingTime()
syncClock()
function displayRemainingTime() {
if (deadline < now()) deadline.setDate(deadline.getDate() + 1)
const remainingTime = deadline - now()
const extract = (maximum, factor) => Math.floor((remainingTime % maximum) / factor)
const seconds = extract( 60000, 1000 )
const minutes = extract( 3600000, 60000 )
const hours = extract(86400000, 3600000)
span.innerText = `${hours} hours ${minutes} minutes ${seconds} seconds remaining`
}
function syncClock() {
const xmlhttp = new XMLHttpRequest();
xmlhttp.open("HEAD", "http://www.googleapis.com",true);
xmlhttp.onreadystatechange = function() {
const referenceTime = new Date
if (xmlhttp.readyState==4) {
const correctTime = new Date(xmlhttp.getResponseHeader("Date"))
timeDrift = correctTime - referenceTime
}
}
xmlhttp.send(null);
}
<h3>
<span id="countdown"></span>
</h3>
I am not sure how Shopify handles plugins, but there must be some way to edit CSS for them, so you could have them match the style of your theme.
What you've done here, in the JS you've provided, will always have that behavior because it is client-side code. The script will run after each refresh, and will always refresh the values minutes and seconds to the associated initial values namely 1 and 5. I believe this answers your first question.
As per your second question, you clearly have not coded hours in that JS script. So hours should not appear, it would be a mystery if they did!
With respect to your third question, you only call countdown once during the onload function.
And by the first answer, it is natural that the clock should not be synchronized among users since they would logically be refreshing your page at different times.
So I think your best bet is to use one of the plugins and just modify the CSS.

How to convert seconds to HH:mm:ss in moment.js

How can I convert seconds to HH:mm:ss?
At the moment I am using the function below
render: function (data){
return new Date(data*1000).toTimeString().replace(/.*(\d{2}:\d{2}:\d{2}).*/, "$1");;
}
This works on chrome but in firefox for 12 seconds I get 01:00:12
I would like to use moment.js for cross browser compatibility
I tried this but does not work
render: function (data){
return moment(data).format('HH:mm:ss');
}
What am I doing wrong?
EDIT
I managed to find a solution without moment.js which is as follow
return (new Date(data * 1000)).toUTCString().match(/(\d\d:\d\d:\d\d)/)[0];
Still curious on how I can do it in moment.js
This is similar to the answer mplungjan referenced from another post, but more concise:
const secs = 456;
const formatted = moment.utc(secs*1000).format('HH:mm:ss');
document.write(formatted);
<script src="https://cdnjs.cloudflare.com/ajax/libs/moment.js/2.18.1/moment.min.js"></script>
It suffers from the same caveats, e.g. if seconds exceed one day (86400), you'll not get what you expect.
From this post I would try this to avoid leap issues
moment("2015-01-01").startOf('day')
.seconds(s)
.format('H:mm:ss');
I did not run jsPerf, but I would think this is faster than creating new date objects a million times
function pad(num) {
return ("0"+num).slice(-2);
}
function hhmmss(secs) {
var minutes = Math.floor(secs / 60);
secs = secs%60;
var hours = Math.floor(minutes/60)
minutes = minutes%60;
return `${pad(hours)}:${pad(minutes)}:${pad(secs)}`;
// return pad(hours)+":"+pad(minutes)+":"+pad(secs); for old browsers
}
function pad(num) {
return ("0"+num).slice(-2);
}
function hhmmss(secs) {
var minutes = Math.floor(secs / 60);
secs = secs%60;
var hours = Math.floor(minutes/60)
minutes = minutes%60;
return `${pad(hours)}:${pad(minutes)}:${pad(secs)}`;
// return pad(hours)+":"+pad(minutes)+":"+pad(secs); for old browsers
}
for (var i=60;i<=60*60*5;i++) {
document.write(hhmmss(i)+'<br/>');
}
/*
function show(s) {
var d = new Date();
var d1 = new Date(d.getTime()+s*1000);
var hms = hhmmss(s);
return (s+"s = "+ hms + " - "+ Math.floor((d1-d)/1000)+"\n"+d.toString().split("GMT")[0]+"\n"+d1.toString().split("GMT")[0]);
}
*/
You can use moment-duration-format plugin:
var seconds = 3820;
var duration = moment.duration(seconds, 'seconds');
var formatted = duration.format("hh:mm:ss");
console.log(formatted); // 01:03:40
<!-- Moment.js library -->
<script src="https://cdnjs.cloudflare.com/ajax/libs/moment.js/2.18.1/moment.min.js"></script>
<!-- moment-duration-format plugin -->
<script src="https://cdnjs.cloudflare.com/ajax/libs/moment-duration-format/1.3.0/moment-duration-format.min.js"></script>
See also this Fiddle
Upd: To avoid trimming for values less than 60-sec use { trim: false }:
var formatted = duration.format("hh:mm:ss", { trim: false }); // "00:00:05"
var seconds = 2000 ; // or "2000"
seconds = parseInt(seconds) //because moment js dont know to handle number in string format
var format = Math.floor(moment.duration(seconds,'seconds').asHours()) + ':' + moment.duration(seconds,'seconds').minutes() + ':' + moment.duration(seconds,'seconds').seconds();
My solution for changing seconds (number) to string format (for example: 'mm:ss'):
const formattedSeconds = moment().startOf('day').seconds(S).format('mm:ss');
Write your seconds instead 'S' in example.
And just use the 'formattedSeconds' where you need.
In a better way to utiliza moments.js; you can convert the number of seconds to human-readable words like ( a few seconds, 2 minutes, an hour).
Example below should convert 30 seconds to "a few seconds"
moment.duration({"seconds": 30}).humanize()
Other useful features: "minutes", "hours"
The above examples may work for someone but none did for me, so I figure out a much simpler approach
var formatted = moment.utc(seconds*1000).format("mm:ss");
console.log(formatted);
Until 24 hrs.
As Duration.format is deprecated, with moment#2.23.0
const seconds = 123;
moment.utc(moment.duration(seconds,'seconds').as('milliseconds')).format('HH:mm:ss');
How to correctly use moment.js durations?
|
Use moment.duration() in codes
First, you need to import moment and moment-duration-format.
import moment from 'moment';
import 'moment-duration-format';
Then, use duration function. Let us apply the above example: 28800 = 8 am.
moment.duration(28800, "seconds").format("h:mm a");
🎉Well, you do not have above type error. 🤔Do you get a right value 8:00 am ? No…, the value you get is 8:00 a. Moment.js format is not working as it is supposed to.
💡The solution is to transform seconds to milliseconds and use UTC time.
moment.utc(moment.duration(value, 'seconds').asMilliseconds()).format('h:mm a')
All right we get 8:00 am now. If you want 8 am instead of 8:00 am for integral time, we need to do RegExp
const time = moment.utc(moment.duration(value, 'seconds').asMilliseconds()).format('h:mm a');
time.replace(/:00/g, '')
To display number of days along with hours, mins and seconds, you can do something like this:
const totalSec = 126102;
const remainingMillies= (totalSec % 86400) * 1000;
const formatted = `${Math.floor(totalSec / 86400)} day(s) and ${moment.utc(remainingMillies).format('hh:mm:ss')}`;
console.log(formatted );
will output :
1 day(s) and 11:01:42
In 2022 no need for any new plugin just do this
Literally all you need in 2022 prints out duration in hh:mm:ss from two different date strings
<Moment format='hh:mm:ss' duration={startTime} date={endTime} />
I think there's no need to use 3rd part libray/pluggin to get this task done
when using momentJS version 2.29.4 :
private getFormatedDuration(start: Date, end: Date): string {
// parse 'normal' Date values to momentJS values
const startDate = moment(start);
const endDate = moment(end);
// calculate and convert to momentJS duration
const duration = moment.duration(endDate.diff(startDate));
// retrieve wanted values from duration
const hours = duration.asHours().toString().split('.')[0];
const minutes = duration.minutes();
// voilà ! without using any 3rd library ..
return `${hours} h ${minutes} min`;
}
supports also 24h format
PS : you can test and calculate by yourself using a 'decimal to time' calculator at CalculatorSoup

In JavaScript, how can I have a function run at a specific time?

I have a website that hosts a dashboard: I can edit the JavaScript on the page and I currently have it refreshing every five seconds.
I am trying to now get a window.print() to run every day at 8 AM.
How could I do this?
JavaScript is not the tool for this. If you want something to run at a specific time every day, you're almost certainly looking for something that runs locally, like python or applescript.
However, let's consider for a moment that JavaScript is your only option. There are a few ways that you could do this, but I'll give you the simplest.
First, you'll have to to create a new Date() and set a checking interval to see whether the hour is 8 (for 8 AM).
This will check every minute (60000 milliseconds) to see if it is eight o'clock:
window.setInterval(function(){ // Set interval for checking
var date = new Date(); // Create a Date object to find out what time it is
if(date.getHours() === 8 && date.getMinutes() === 0){ // Check the time
// Do stuff
}
}, 60000); // Repeat every 60000 milliseconds (1 minute)
It won't execute at exactly 8 o'clock (unless you start running this right on the minute) because it is checking once per minute. You could decrease the interval as much as you'd like to increase the accuracy of the check, but this is overkill as it is: it will check every minute of every hour of every day to see whether it is 8 o'clock.
The intensity of the checking is due to the nature of JavaScript: there are much better languages and frameworks for this sort of thing. Because JavaScript runs on webpages as you load them, it is not meant to handle long-lasting, extended tasks.
Also realize that this requires the webpage that it is being executed on to be open. That is, you can't have a scheduled action occur every day at 8 AM if the page isn't open doing the counting and checking every minute.
You say that you are already refreshing the page every five seconds: if that's true, you don't need the timer at all. Just check every time you refresh the page:
var date = new Date(); // Create Date object for a reference point
if(date.getHours() === 8 && date.getMinutes() === 0 && date.getSeconds() < 10){ // Check the time like above
// Do stuff
}
With this, you also have to check the seconds because you're refreshing every five seconds, so you would get duplicate tasks.
With that said, you might want to do something like this or write an Automator workflow for scheduled tasks on OS X.
If you need something more platform-agnostic, I'd seriously consider taking a look at Python or Bash.
As an update, JavaScript for Automation was introduced with OS X Yosemite, and it seems to offer a viable way to use JavaScript for this sort of thing (although obviously you're not using it in the same context; Apple is just giving you an interface for using another scripting language locally).
If you're on OS X and really want to use JavaScript, I think this is the way to go.
The release notes linked to above appear to be the only existing documentation as of this writing (which is ~2 months after Yosemite's release to the public), but they're worth a read. You can also take a look at the javascript-automation tag for some examples.
I've also found the JXA Cookbook extremely helpful.
You might have to tweak this approach a bit to adjust for your particular situation, but I'll give a general overview.
Create a blank Application in Automator.
Open Automator.app (it should be in your Applications directory) and create a new document.
From the dialog, choose "Application."
Add a JavaScript action.
The next step is to actually add the JavaScript that will be executed. To do that, start by adding a "Run JavaScript" action from the sidebar to the workflow.
Write the JavaScript.
This is where you'll have to know what you want to do before proceeding. From what you've provided, I'm assuming you want to execute window.print() on a page loaded in Safari. You can do that (or, more generally, execute arbitrary JS in a Safari tab) with this:
var safari = Application('Safari');
safari.doJavaScript('window.print();', { in: safari.windows[0].currentTab });
You might have to adjust which of the windows you're accessing depending on your setup.
Save the Application.
Save (File -> Save or ⌘+S) the file as an Application in a location you can find (or iCloud).
Schedule it to run.
Open Calendar (or iCal).
Create a new event and give it an identifiable name; then, set the time to your desired run time (8:00 AM in this case).
Set the event to repeat daily (or weekly, monthly, etc. – however often you'd like it to run).
Set the alert (or alarm, depending on your version) to custom.
Choose "Open file" and select the Application file that you saved.
Choose "At time of event" for the alert timing option.
That's it! The JavaScript code that you wrote in the Application file will run every time that event is set to run. You should be able to go back to your file in Automator and modify the code if needed.
function every8am (yourcode) {
var now = new Date(),
start,
wait;
if (now.getHours() < 7) {
start = new Date(now.getFullYear(), now.getMonth(), now.getDate(), 8, 0, 0, 0);
} else {
start = new Date(now.getFullYear(), now.getMonth(), now.getDate() + 1, 8, 0, 0, 0);
}
wait = start.getTime() - now.getTime();
if(wait <= 0) { //If missed 8am before going into the setTimeout
console.log('Oops, missed the hour');
every8am(yourcode); //Retry
} else {
setTimeout(function () { //Wait 8am
setInterval(function () {
yourcode();
}, 86400000); //Every day
},wait);
}
}
To use it:
var yourcode = function () {
console.log('This will print evryday at 8am');
};
every8am(yourcode);
Basically, get the timestamp of now, the timestamp of today 8am if run in time, or tomorrow 8am, then set a interval of 24h to run the code everyday. You can easily change the hour it will run by setting the variable start at a different timestamp.
I don t know how it will be useful to do that thought, as other pointed out, you ll need to have the page open all day long to see that happen...
Also, since you are refreshing every 5 seconds:
function at8am (yourcode) {
var now = new Date(),
start = new Date(now.getFullYear(), now.getMonth(), now.getDate(), 8, 0, 0, 0);
if (now.getTime() >= start.getTime() - 2500 && now.getTime() < start.getTime() + 2500) {
yourcode();
}
}
Run it the same way as every8am, it look if 8am is 2.5second ahead or behind, and run if it does.
I try to give my answer hoping it could help:
function startJobAt(hh, mm, code) {
var interval = 0;
var today = new Date();
var todayHH = today.getHours();
var todayMM = today.getMinutes();
if ((todayHH > hh) || (todayHH == hh && todayMM > mm)) {
var midnight = new Date();
midnight.setHours(24,0,0,0);
interval = midnight.getTime() - today.getTime() +
(hh * 60 * 60 * 1000) + (mm * 60 * 1000);
} else {
interval = (hh - todayHH) * 60 * 60 * 1000 + (mm - todayMM) * 60 * 1000;
}
return setTimeout(code, interval);
}
With the startJobAt you can execute only one the task you wish, but if you need to rerun your task It's up to you to recall startJobAt.
bye
Ps
If you need an automatic print operation, with no dialog box, consider to use http://jsprintsetup.mozdev.org/reference.html plugin for mozilla or other plugin for other bowsers.
I will suggest to do it in Web Worker concept, because it is independent of other scripts and runs without affecting the performance of the page.
Create a web worker (demo_worker.js)
var i = 0;
var date = new Date();
var counter = 10;
var myFunction = function(){
i = i + 1;
clearInterval(interval);
if(date.getHours() === 8 && date.getMinutes() === 0) {
counter = 26280000;
postMessage("hello"+i);
}
interval = setInterval(myFunction, counter);
}
var interval = setInterval(myFunction, counter);
Use the web worker in Ur code as follows.
var w;
function startWorker() {
if (typeof(Worker) !== "undefined") {
if (typeof(w) == "undefined") {
w = new Worker("demo_worker.js");
w.onmessage = function(event) {
window.print();
};
} else {
document.getElementById("result").innerHTML = "Sorry, your browser does not support HTML5 Web Workers";
}
}
}
I think it will help you.
I have written function which
allows expressing delay in seconds, new Date() format and string's new Date format
allows cancelling timer
Here is code:
"use strict"
/**
This function postpones execution until given time.
#delay might be number or string or `Date` object. If number, then it delay expressed in seconds; if string, then it is parsed with new Date() syntax. Example:
scheduleAt(60, function() {console.log("executed"); }
scheduleAt("Aug 27 2014 16:00:00", function() {console.log("executed"); }
scheduleAt("Aug 27 2014 16:00:00 UTC", function() {console.log("executed"); }
#code function to be executed
#context #optional `this` in function `code` will evaluate to this object; by default it is `window` object; example:
scheduleAt(1, function(console.log(this.a);}, {a: 42})
#return function which can cancel timer. Example:
var cancel=scheduleAt(60, function(console.log("executed.");});
cancel();
will never print to the console.
*/
function scheduleAt(delay, code, context) {
//create this object only once for this function
scheduleAt.conv = scheduleAt.conv || {
'number': function numberInSecsToUnixTs(delay) {
return (new Date().getTime() / 1000) + delay;
},
'string': function dateTimeStrToUnixTs(datetime) {
return new Date(datetime).getTime() / 1000;
},
'object': function dateToUnixTs(date) {
return date.getTime() / 1000;
}
};
var delayInSec = scheduleAt.conv[typeof delay](delay) - (new Date().getTime() / 1000);
if (delayInSec < 0) throw "Cannot execute in past";
if (debug) console.log('executing in', delayInSec, new Date(new Date().getTime() + delayInSec * 1000))
var id = setTimeout(
code,
delayInSec * 1000
);
//preserve as a private function variable setTimeout's id
return (function(id) {
return function() {
clearTimeout(id);
}
})(id);
}
Use this as follows:
scheduleAt(2, function() {
console.log("Hello, this function was delayed 2s.");
});
scheduleAt(
new Date().toString().replace(/:\d{2} /, ':59 '),
function() {
console.log("Hello, this function was executed (almost) at the end of the minute.")
}
);
scheduleAt(new Date(Date.UTC(2014, 9, 31)), function() {
console.log('Saying in UTC time zone, we are just celebrating Helloween!');
})
setInterval(() => {
let t = `${new Date().getHours() > 12 ? new Date().getHours() - 12 : new Date().getHours()}:${new Date().getMinutes().length < 2 ? '0' + new Date().getMinutes() : new Date().getMinutes()}:${new Date().getSeconds().length < 2 ? '0' + new Date().getSeconds() : new Date().getSeconds()} ${new Date().getHours()>12?"pm":"am"}`
console.log(t);
}, 1000);

Categories