Formatting time from seconds to HH:MM:SS in a countdown - javascript

I am having this simple countdown:
function offer_countdown_timer(countdown_start, countdown_time, update, complete) {
var start = new Date(countdown_start).getTime();
var interval = setInterval(function() {
var now = countdown_time-(new Date().getTime()-start);
if( now <= 0) {
clearInterval(interval);
complete();
} else {
update(Math.floor(now/1000));
}
},100); // the smaller this number, the more accurate the timer will be
}
and here I call it:
<script>
offer_countdown_timer(
'<%= s.created_at%>',
3600000, // 1 hour in milliseconds
function(timeleft) { // called every step to update the visible countdown
var txt = timeleft+' seconds';
$('#tender_countdown_<%= s.id %>').html(txt);
//$('#tender_countdown_<%= s.id %>').html(moment(txt).format('HH:mm:ss'));
},
function() {
$('#product_<%= s.id %>').html('Offer has expired!');
}
);
</script>
Output of this is:
773 seconds
(and it's counting down)
I'd like to see something like this (HH:ss:mm):
00:12:53
(and counting it down).
I tried this to use this (with using the Moment.js lib - https://momentjs.com/docs/):
$('#tender_countdown_<%= s.id %>').html(moment(txt).format('HH:mm:ss'));
But in this case, the output is this:
01:00:00
The time information is wrong, and it's not counting down. Why is that? How do I properly format the countdowning time?
Thank you

The number of seconds is an abstract duration of time, rather than a date representing a specific moment in time. Moment's constructor expects you to give it a date string.
Moment has a Duration object which can parse your data. It doesn't have nice formatting functions yet, but you can construct the desired output easily enough:
var txt = 773;
var m = moment.duration(txt, "s");
var output = m.hours() + ":" + m.minutes() + ":" + m.seconds();
console.log(output);
<script src="https://cdnjs.cloudflare.com/ajax/libs/moment.js/2.24.0/moment.min.js"></script>
See https://momentjs.com/docs/#/durations/ for more details.

Related

How can i make something happen in a time range?

I want a box to popup at 14:00. Later i want it to disappear at 16:00. How can i do this? I am using Android Studio. I want it to be something like this:
if (Calendar.HOUR_OF_DAY > 14) {
Log.d("TIME", "Time Works!");
}
I'm unsure about Android Studio, but for JavaScript alone, you can use the setTimeout() function to invoke some task every X amount of time. Set this up to check the current time every once in a while, and if it's more than 14:00 and less than 16:00, make sure your popup is shown, otherwise close it...
setTimeout(handlePopupVisibility, 60000);
function handlePopupVisibility() {
var now = new Date();
var startTime = dateObj('2:00 PM');
var endTime = dateObj('4:00 PM');
if (now < dateEnd && now > startTime) {
// inside the range, show your element
// (assumes jQuery)
$("#popupID").show();
} else {
// outside the range, hide your element
// (assumes jQuery)
$("#popupID").hide();
}
}
function dateObj(d) {
var parts = d.split(/:|\s/),
date = new Date();
if (parts.pop().toLowerCase() == 'pm') parts[0] = (+parts[0]) + 12;
date.setHours(+parts.shift());
date.setMinutes(+parts.shift());
return date;
}
(stolen from answer here: How to check if current time falls within a specific range considering also minutes )

Function to iterate over an array of dates produces unexpected results

I have a CloudCode function that is called from my iOS app. The function is supposed to create a "checkin" record and return a string to represent the last 30 days of check-ins and missed days.
The strange thing is that sometimes I get the expected results and sometimes I do not. It makes me think that there is some issue with the may I am using timezones - since that could result in a different set of "days in the past" depending on what time I run this function and what time of day I checked-in in the past. But I'm baffled and could use some help here.
It's also confusing me that I do not see all of my console.log() results appear in the parse log. Is that normal?? For example, in the for loop, I can uncomment the console.log entry and call the function but I will not see all of the days in the past listed - but they are included in the final array and text string.
Here is my complete function. Any help and suggestions are appreciated.
/* Function for recording a daily check in
*
* Calculates the number of days missed and updates the string used to display the check-in pattern.
* If no days missed then we increment the current count
*
* Input:
* "promiseId" : objectID,
* "timeZoneDifference" : String +07:00
*
* Output:
* JSON String eg. {"count":6,"string":"000000000000001111101010111111"}
*
*/
Parse.Cloud.define("dailyCheckIn", function(request, response) {
var promiseId = request.params.promiseId;
var timeZoneDifference = request.params.timeZoneDifference;
var currentUser = Parse.User.current();
if (currentUser === undefined) {
response.error("You must be logged in.");
}
if (timeZoneDifference === undefined || timeZoneDifference === "") {
//console.log("timeZoneDifference missing. Set to -07:00");
timeZoneDifference = '' + '-07:00'; // PacificTime as string
}
var moment = require('cloud/libs/moment.js');
// Query for the Promise
var Promise = Parse.Object.extend("Promise");
var queryforPromise = new Parse.Query(Promise);
queryforPromise.get(promiseId, {
success: function(promis) {
// Initialize
var dinarowString = "";
var dinarowCount = 0;
// Last Check In date from database (UTC)
var lastCheckInUTC = promis.get("lastCheckIn");
if (lastCheckInUTC === undefined) {
lastCheckInUTC = new Date(2015, 1, 1);
}
// Use moment() to convert lastCheckInUTC to local timezone
var lastCheckInLocalized = moment(lastCheckInUTC.toString()).utcOffset(timeZoneDifference);
//console.log('lastCheckIn: ' + lastCheckInUTC.toString());
//console.log('lastCheckInLocalized: ' + lastCheckInLocalized.format());
// Use moment() to get "now" in UTC timezone
var today = moment().utc(); // new Date();
//console.log('today: ' + today.format());
// Use moment() to get "now" in local timezone
var todayLocalized = today.utcOffset(timeZoneDifference);
//console.log('todayLocalized: ' + todayLocalized.format());
// 30 days in the past
var thirtydaysago = moment().utc().subtract(30, 'days');
//console.log("thirtydaysago = " + thirtydaysago.format());
// 30 days in the past in local timezone
var thirtydaysagoLocalized = thirtydaysago.utcOffset(timeZoneDifference);
//console.log('thirtydaysagoLocalized: ' + thirtydaysagoLocalized.format());
// Calculate the number of days since last time user checked in
var dayssincelastcheckin = todayLocalized.diff(lastCheckInLocalized, 'days');
//console.log("Last check-in was " + dayssincelastcheckin + " days ago");
// Function takes an array of Parse.Objects of type Checkin
// itterate over the array to get a an array of days in the past as numnber
// generate a string of 1 and 0 for the past 30 days where 1 is a day user checked in
function dinarowStringFromCheckins(checkins) {
var days_array = [];
var dinarowstring = "";
// Create an array entry for every day that we checked in (daysago)
    for (var i = 0; i < checkins.length; i++) {
var checkinDaylocalized = moment(checkins[i].get("checkInDate")).utcOffset(timeZoneDifference);
var daysago = todayLocalized.diff(checkinDaylocalized, 'days');
// console.log("daysago = " + daysago);
days_array.push(daysago);
}
console.log("days_array = " + days_array);
// Build the string with 30 day of hits "1" and misses "0" with today on the right
    for (var c = 29; c >= 0; c--) {
if (days_array.indexOf(c) != -1) {
//console.log("days ago (c) = " + c + "-> match found");
dinarowstring += "1";
} else {
dinarowstring += "0";
}
}
return dinarowstring;
}
// Define ACL for new Checkin object
var checkinACL = new Parse.ACL();
checkinACL.setPublicReadAccess(false);
checkinACL.setReadAccess(currentUser, true);
checkinACL.setWriteAccess(currentUser, true);
// Create a new entry in the Checkin table
var Checkin = Parse.Object.extend("Checkin");
var checkin = new Checkin();
checkin.set("User", currentUser);
checkin.set("refPromise", promis);
checkin.set("checkInDate", today.toDate());
checkin.setACL(checkinACL);
checkin.save().then(function() {
// Query Checkins
var Checkin = Parse.Object.extend("Checkin");
var queryforCheckin = new Parse.Query(Checkin);
queryforCheckin.equalTo("refPromise", promis);
queryforCheckin.greaterThanOrEqualTo("checkInDate", thirtydaysago.toDate());
queryforCheckin.descending("checkInDate");
queryforCheckin.find().then(function(results) {
var dinarowString = "000000000000000000000000000000";
var dinarowCount = 0;
if (results.length > 0) {
dinarowString = dinarowStringFromCheckins(results);
dinarowIndex = dinarowString.lastIndexOf("0");
if (dinarowIndex === -1) { // Checked in every day in the month!
// TODO
// If the user has checked in every day this month then we need to calculate the
// correct streak count in a different way
dinarowString = "111111111111111111111111111111";
dinarowCount = 999;
} else {
dinarowCount = 29 - dinarowIndex;
}
}
// Update the promise with new value and save
promis.set("dinarowString", dinarowString);
promis.set("dinarowCount", dinarowCount);
promis.set("lastCheckIn", today.toDate());
promis.save().then(function() {
response.success(JSON.stringify({
count: dinarowCount,
string: dinarowString
}));
});
}, function(reason) {
console.log("Checkin query unsuccessful:" + reason.code + " " + reason.message);
response.error("Something went wrong");
});
}); // save.then
},
error: function(object, error) {
console.error("dailyCheckIn failed: " + error);
response.error("Unable to check-in. Try again later.");
}
});
});
There's too much going on in your question to answer adequately, but I will be nice and at least point out a few errors that you should look into:
You take input in terms of a fixed offset, but then you are doing operations that subtract 30 days. It's entirely possible that you will cross a daylight saving time boundary, in which case the offset will have changed.
See "Time Zone != Offset" in the timezone tag wiki. In moment, you can use time zones names like "America/Los_Angeles" with the moment-timezone add-on.
From your example, I'm not even sure if time zone even matters or not for your use case.
You should not convert the Date to a string just to parse it again. Moment can accept a Date object, assuming the Date object was created correctly.
moment(lastCheckInUTC.toString()).utcOffset(timeZoneDifference)
becomes
moment(lastCheckInUTC).utcOffset(timeZoneDifference)
Since Date.toString() returns a locale-specific, implementation-specific format, you'll also see you have a warning in the debug console from moment.
As for the rest, we can't run your program and reproduce the results, so there's not much we can do to help. You need to start by debugging your own program, and then try to reproduce your error in a Minimal, Complete, and Verifiable example. Chances are, you'll solve your own problem along the way. If not, then you will have something in a better state to share with us.
I am answering my own question as I have found the solution.
I had two questions. The first was "why do I get unexpected (incorrect) results" and I suspected that it was related to the way I am using timezones. I would see different results from day to day depending on what time I check in.
The problem is actually related to the way that moment().diff() works. Diff does not calculate "days" the way I expected it to. If I compare 2am today with 11pm yesterday diff will say 0 days because it is less than 24 hours diff. If I compare 1am on Thursday with 8pm on the previous Monday, diff will report 2 days - not 3 as I expected. It's a precision issue. Diff thinks 2.4 days is 2 days ago. But it is more than 2 therefor it is 3 days ago.
We found that the easiest solution is to compare the two dates at midnight rather than at the actual time of day that is recorded in the database. This yields correct results for days. The rest of the code is working fine.
//Find start time of today's day
var todayLocalizedStart = todayLocalized.startOf('day');
    for (var i = 0; i < checkins.length; i++) {
var checkinDaylocalized = moment(checkins[i].get("checkInDate")).utcOffset(timeZoneDifference);
//Find start time of checkIn day
var checkinDaylocalizedStart = checkinDaylocalized.startOf('day');
//Find number of days
var daysago = todayLocalizedStart.diff(checkinDaylocalizedStart, 'days');
// console.log("daysago = " + daysago);
days_array.push(daysago);
}
The second question I had was "is it normal to not see every console.log at runtime". I've talked with other Parse.com users and they report that Parse is inconsistent in logging. I was spending a lot of time debugging "problems" that were simply Parse not logging correctly.
Thanks to everyone that contributed to the answer.
I did make one other change - but it was not a bug. I replaced the query limit from 30 days in the past to simply "30". It's just a bit simpler with one less calculation.

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

how to update time regularly?

function timeClock()
{
setTimeout("timeClock()", 1000);
now = new Date();
alert(now);
f_date = now.getDate()+" "+strMonth(now.getMonth())+" "+now.getFullYear()+" / "+timeFormat(now.getHours(), now.getMinutes());
return f_date;
}
<span class="foo"><script type="text/javascript">document.write(timeClock());</script></span>
alert(now); gives me the value every second but it is not updated in the html. How can I update the time on the html without refresh the page?
There are a number of mistakes in your code. Without the use of var infront of your variable declarations, you leak them into the global scope.
Also, the use of document.write is discouraged.
Here's how I would do it:
JavaScript:
function updateClock() {
var now = new Date(), // current date
months = ['January', 'February', '...']; // you get the idea
time = now.getHours() + ':' + now.getMinutes(), // again, you get the idea
// a cleaner way than string concatenation
date = [now.getDate(),
months[now.getMonth()],
now.getFullYear()].join(' ');
// set the content of the element with the ID time to the formatted string
document.getElementById('time').innerHTML = [date, time].join(' / ');
// call this function again in 1000ms
setTimeout(updateClock, 1000);
}
updateClock(); // initial call
HTML:
<div id="time"> </div>
setInterval(expression, timeout);
The function setTimeout is intended for a single timeout, so using setInterval would be a more appropriate option. SetInterval will run regularly without the additional lines that Ivo's answer has.
I would rewrite Ivo's answer as follows:
JavaScript:
function updateClock() {
// Ivo's content to create the date.
document.getElementById('time').innerHTML = [date, time].join(' / ')
}
setInterval(updateClock, 1000);
Try it out yourself! https://jsfiddle.net/avotre/rtuna4x7/2/
x = document.getElementsByTagName('SPAN').item(0);
x.innerHTML = f_date;
try putting this code block instead of return statement, i haven't test it but it will probably work
There may be something in timeago jQuery plugin you can hook into, but I haven't honestly tried...
http://timeago.yarp.com/
$('span.foo').html(f_date);
place this inside your timeclock() function
untested
function timeClock()
{
setTimeout("timeClock()", 1000);
now = new Date();
alert(now);
f_date = now.getDate()+" "+strMonth(now.getMonth())+" "+now.getFullYear()+" / "+timeFormat(now.getHours(), now.getMinutes());
$('span.foo').html(f_date);
}
I'd use setInterval rather than setTimeout:
https://developer.mozilla.org/en/DOM/window.setInterval
I think your setTmeout function has the wrong variables, the first one should be a function not a string, that confused me for a bit. Basically you need to write to the span tag when you run the function.
I created a jQuery version in a fiddle to demonstrate what I mean. Didn't have your strMonth function but you get the idea. I also changed the alert to console.log but you can remove that line.
http://jsfiddle.net/5JWEV/
Straigt Javascript time format / update
1: create month converter func
2: create time func
3: create update func
4: create outPut func
// month converter from index / 0-11 values
function covertMonth(num){
let months = ['Jan','Feb','Mar','Apr','May','Jun','Jul','Aug','Sep','Oct','Nov','Dec'];
// look into index with num 0-11
let computedRes = months[num];
return computedRes;
}
// time func
function Time(){
// important to get new instant of the Date referrance
let date = new Date();
this.time = date.toLocaleTimeString();
this.year = date.getUTCFullYear();
this.day = date.getUTCDate();
this.month = date.getUTCMonth();
this.currentTime = date.toLocaleTimeString() + ' ' + covertMonth(this.month) + ' ' + this.day + ' ' + this.year;
return this.currentTime;
}
function timeOutPut(){
let where = document.getElementById('some-id');
where.textContent = Time(); // 1:21:39 AM Dec 17 2017
}
// run every 5secs
setInterval(timeOutPut, 5000);
I used #soloproper setInterval concept #Ivo Wetzel overall answer, my update is all about formatting the time as required. Reduced Programming Lines
<div id="liveClock"> </div>
$(document).ready(function () {
updateClock();
});
function updateClock() {
document.getElementById('liveClock').innerHTML = new Date().format("dd/MMMM/yyyy hh:mm:ss tt");
}
setInterval(updateClock, 1000);
function timeClock()
{
setTimeout("timeClock()", 1000);
now = new Date();
alert(now);
f_date = now.getDate()+" "+strMonth(now.getMonth())+" "+now.getFullYear()+" / "+timeFormat(now.getHours(), now.getMinutes());
document.getElementById("foo").innerHTML = f_date;
}
<span id="foo"></span>

Categories