Reverse a list of HTML paragraph via Javascript - javascript

I'm using Javascript (no jQuery) to create a list of paragraphs to get the best time to go to sleep (based on the REM sleep cycle) and show it on a page, here's the code.
function sleepnow() {
var result = '';
var a = new Date();
var hour = a.getHours();
var minutes = a.getMinutes() + 14;
if (minutes > 60) {
minutes = minutes - 60;
hour = hour + 1;
}
for (var counter = 0; counter < 6; counter++) {
if (minutes < 30) {
minutes = minutes + 30;
} else {
minutes = minutes - 30;
hour = hour + 1;
}
hour = hour + 1;
if (hour >= 24) {
if (hour === 24) {
hour = 0;
} else if (hour === 25) {
hour = 1;
}
}
if (hour > 9) {
result = result + '<p>' + hour;
} else {
result = result + '<p>0' + hour;
}
if (minutes > 9) {
result = result + ':' + minutes + '</p>';
} else {
result = result + ':0' + minutes + '</p>';
}
}
document.getElementById('sleepnow').innerHTML = result;
}
How can I reverse that list to show the farther one first and so on? I tried for an hour with .reverse() but I can't get it to work, it just flips everything, < p > tags included, breaking everything.

I'd separate the data from the html a little more. Instead of building a string, build an array of times. Then you can loop through it in reverse order when you build the html string.
1. create data structure, contains only numbers, no html (model)
2. convert data to html (view)
var html = '';
for (var counter = YOURDATA.length-1; counter >= 0; counter--) {
var t = YOURDATA[counter];
html += ' build your string ' + t + '...';
}
Also this case should be fine, but be careful with special characters in the raw data (&<>\""). Generally you should escape all the data, for an html context.

First of all: The answer is: By using an intermediate accumulator string variable currentOne which accumulates normally and by accumulating in the other order in the result: result = currentOne + result instead of result = result + currentOne. Enjoy:
function sleepnow() {
var result = '';
var a = new Date();
var hour = a.getHours();
var minutes = a.getMinutes() + 14;
if (minutes > 60) {
minutes = minutes - 60;
hour = hour + 1;
}
for (var counter = 0; counter < 6; counter++) {
var currentOne = "";
if (minutes < 30) {
minutes = minutes + 30;
} else {
minutes = minutes - 30;
hour = hour + 1;
}
hour = hour + 1;
if (hour >= 24) {
if (hour === 24) {
hour = 0;
} else if (hour === 25) {
hour = 1;
}
}
if (hour > 9) {
currentOne = currentOne + '<p>' + hour;
} else {
currentOne = currentOne + '<p>0' + hour;
}
if (minutes > 9) {
currentOne = currentOne + ':' + minutes + '</p>';
} else {
currentOne = currentOne + ':0' + minutes + '</p>';
}
result = currentOne + result;
}
document.getElementById('sleepnow').innerHTML = result;
}
Secondly: Please don't make external links without describing what's on the other side thoroughly. External links can expire, become irrelevant, etc.
Third: You made quite a mess in that code right there :)

Related

How to reduce time using Javascript?

How can I use reduce() to calculate the total of all times (in string format) in the following array?
time["00:30", "01:45", "02:33"]
times.reduce((time, nextTime) => time + nextTime, 0)
I was thinking I need to split(":"), parseInt() and some more calculations or is there an easier way to do this?
If you can use an open JavaScript library like moment.js, the following is simple and preserves your string formatted times.
Note that I'm passing in "00:00" as the default value to reduce() so that times are calculated from a zero baseline, which also follows the string formatting that we'll use for all other values in the array.
const times["00:30", "01:45", "02:33"]
const totalTime = times.reduce((time, nextTime) => {
return moment(time, "hh:mm")
.add(nextTime, "hh:mm")
.format("hh:mm");
}, "00:00");
console.log("total time -->", totalTime);
// total time --> "04:48"
If we added logging inside reduce() to view the accumulation of values:
"12:30"
"02:15"
"04:48"
"total time -->" "04:48"
Notice that the result after the first pass was "12:30". If all times in the array summed to less than one clock hour the end result may not be acceptable for your particular use case.
This worked for me, this function timer is taking 2 times hh:mm:ss and splits it, divides, and then adds them together and after, it formats it to hh:mm:ss again
function timer(tempo1, tempo2) {
var array1 = tempo1.split(":");
var tempo_seg1 =
parseInt(array1[0]) * 3600 + parseInt(array1[1]) * 60 + parseInt(array1[2]);
var array2 = tempo2.split(":");
var tempo_seg2 =
parseInt(array2[0]) * 3600 + parseInt(array2[1]) * 60 + parseInt(array2[2]);
var tempofinal = parseInt(tempo_seg1) + parseInt(tempo_seg2);
var hours = Math.floor(tempofinal / (60 * 60));
var divisorMinutes = tempofinal % (60 * 60);
var minutes = Math.floor(divisorMinutes / 60);
var divisorSeconds = divisorMinutes % 60;
var seconds = Math.ceil(divisorSeconds);
var counter = "";
if (hours < 10) {
counter = "0" + hours + ":";
} else {
counter = hours + ":";
}
if (minutes < 10) {
counter += "0" + minutes + ":";
} else {
counter += minutes + ":";
}
if (seconds < 10) {
counter += "0" + seconds;
} else {
counter += seconds;
}
return counter;
}
export default timer;
and on my React App I used this code to keep track of the times and add them calling the timer function
const updateTime = () => {
let times = [];
let times2 = [];
if (todos.length > 1) {
for (let i = 0; i < todos.length; i++) {
times.push(todos[i].time + ":00");
}
times2 = times[0];
for (let i = 1; i < times.length; i++) {
times2 = timer(times2, times[i]);
}
times2 = times2.substr(0, 5);
} else if (todos.length == 1) times2 = todos[0].time;
else times2 = "No tasks";
return times2;
};
I only wanted hh:mm but for the sake of future implementation of seconds if needed, I'm going to add ":00" (seconds) and then remove it again using
times2 = times2.substr(0, 5);

How can I use variables when constructing a URL string?

I've been given some JavaScript that creates a digital clock to go onto a webpage. This is working perfectly, however, I'm trying to amend it to wrap the am/pm suffix (or Diem in this code) in span or bold tags so that I can style it differently to the rest of the time in the CSS.
I'm sure this would be really simple for someone that knows what they're doing but I'm really struggling.
Any help would be appreciated, the JavaScript is below:
function renderTime() {
var currentTime = new Date();
var diem = "AM";
var h = currentTime.getHours();
var m = currentTime.getMinutes();
var s = currentTime.getSeconds();
setTimeout('renderTime()',1000);
if (h == 0) {
h = 12;
} else if (h > 12) {
h = h - 12;
diem="PM";
}
if (m < 10) {
m = "0" + m;
}
if (s < 10) {
s = "0" + s;
}
var myClock = document.getElementById('clockDisplay');
myClock.textContent = h + ":" + m + " " + diem;
myClock.innerText = h + ":" + m + " " + diem;
var diem = document.createElement('span');
}
renderTime();
So, I want to do the same thing, but in a URL style, like this: http://example.com/example?h="10"&m="42"
Just concatenate the hour and minute to the URL prefix and return that as a string.
Also, your code produces the wrong diem for times between noon and 12:59, since those should be 12PM.
function getTimeURL() {
var currentTime = new Date();
var diem = "AM";
var h = currentTime.getHours();
var m = currentTime.getMinutes();
var s = currentTime.getSeconds();
if (h == 0) {
h = 12;
} else if (h > 12) {
h = h - 12;
diem="PM";
} else {
diem = "PM";
}
if (m < 10) {
m = "0" + m;
}
var url = `http://example.com/example?h=${h}${diem}&m=${m}`;
return url;
}
console.log(getTimeURL());
I added a bunch of comments to your code that'll hopefully make it easier to understand. I also added a global variable that will store your linkText value as it's changed by the function.
// create a global variable that stores our text for the link.
// Your renderTime() function will update it every second.
var linkText = "";
function renderTime() {
//grab the new date
var currentTime = new Date();
//set diem (whatever that means) to "AM"
var diem = "AM";
//get the hours from our current time
var h = currentTime.getHours();
//get the minutes
var m = currentTime.getMinutes();
//get the seconds
var s = currentTime.getSeconds();
//run this function every 1000 milliseconds
setTimeout('renderTime()', 1000);
//if the hour is 0, set it to twelve instead
if (h == 0) {
h = 12;
//else if the hour is any number higher than 12,
//subtract 12 from its value and change diem to "PM"
} else if (h > 12) {
h = h - 12;
diem = "PM";
}
//if the minutes are 0-9 add a 0 before.
if (m < 10) {
m = "0" + m;
}
//if the seconds are 0-9 add a 0 before.
if (s < 10) {
s = "0" + s;
}
//get our clock element
var myClock = document.getElementById('clockDisplay');
//populate our clock element
myClock.textContent = h + ":" + m + ":" + s + " " + diem;
myClock.innerText = h + ":" + m + ":" + s + " " + diem;
//not sure why you're writing over your AM/PM variable at the end here,
//so I commented it out
//var diem = document.createElement('span');
//set our linkText value to be the current hour and minute
linkText = 'http://example.com/example?h="' + h + '"&m="' + m + '"';
}
//run that thang!
renderTime();
<div id="clockDisplay"></div>

When the militaryHour variable is set to 0, why does the system print 0 and not the hour (variable) I set it which is 12?

I'm trying to build a program which converts military hours to am or pm time.
I expected the output of 0 to be 12 am, but the actual output is 0 am.
const militaryHour = 0;
var hour = 0;
var amOrPm = "am";
if (militaryHour < 12) {
hour = militaryHour;
console.log(hour + " " + amOrPm);
} else if (militaryHour == 12) {
amOrPm = "pm";
hour = 12;
console.log(hour + " " + amOrPm);
} else if (militaryHour < 24) {
amOrPm = "pm";
hour = militaryHour - 12;
console.log(hour + " " + amOrPm);
} else if (militaryHour == 24){
hour = 12;
console.log(hour + " " + amOrPm);
} else {
hour = 12;
console.log(hour + " " + amOrPm);
}
All the code you need
const militaryHour = 0,
hour = (militaryHour + 11) % 12 + 1,
amOrPm = militaryHour % 24 < 12 ? 'am' : 'pm';
No if/else required
Let's follow your logic
const militaryHour = 0;
if (militaryHour < 12)
Ok definitely goes into this if statement because 0<12
hour = militaryHour;
console.log(hour + " " + amOrPm);
Then log whatever militaryHour is, which is 0. This is why your code is printing "0 am"
12am is actually an edge case. You just need to add one more condition
if (militaryHour==0) {
hour = 12;
console.log(hour+" "+amOrPm)
}
In your code, the first branch, if (militaryHour < 12) {...} is true, so we have:
const militaryHour = 0;
var hour = 0;
var amOrPm = "am";
hour = militaryHour;
console.log(hour + " " + amOrPm);
It's pretty clear that we're going to get 0 from this.
Here's a solution: take the 24-hour time mod 12. If we wind up with 0, make it 12. Either way, append A.M./P.M. depending on which half of the day the time falls into. All of this eliminates the error-prone large conditional blocks.
const militaryToNormal = hour =>
(hour % 12 || 12) + (hour % 24 < 12 ? "am" : "pm")
;
for (let i = 0; i < 30; i++) {
console.log(i, "=>", militaryToNormal(i));
}
If you can, prefer moment.js.

JavaScript shipping timer countdown

I have the following JavaScript on my site that shows the amount of time left for an order to be placed for next day delivery.
if (document.getElementById('countdownTimer')) {
pad = function(n, len) { // leading 0's
var s = n.toString();
return (new Array((len - s.length + 1)).join('0')) + s;
};
var timerRunning = setInterval(
function countDown() {
var now = new Date();
if ((now.getDay() >= 1) && (now.getDay() <= 5)) { // Monday to Friday only
var target = 15; // 15:00hrs is the cut-off point
if (now.getHours() < target) { // don't do anything if we're past the cut-off point
var hrs = (target - 1) - now.getHours();
if (hrs < 0) hrs = 0;
var mins = 59 - now.getMinutes();
if (mins < 0) mins = 0;
var secs = 59 - now.getSeconds();
if (secs < 0) secs = 0;
var str = pad(hrs, 2) + ':' + pad(mins, 2) + '.<small>' + pad(secs, 2) + '</small>';
document.getElementById('countdownTimer').innerHTML = str;
}
}
}, 1000
);
}
The problem with this is that on saturday and sunday it just displays 00:00:00 all the time.
What I would like it to do is count the hours over a weekend as is done on this site for example: http://www.nakedwines.com/full_site
JavaScript is really not my area and I'm totally at a loss on how I can change the code to do this. Any help would be appreciated.
Fiddle is here http://jsfiddle.net/rwet0o5f/
I've moved the now.getDay() into variable and now it should be much more readable.
weekday contains 0 on Sunday, 1 on Monday and 6 on Saturday.
On Saturday we add 48 hours to the time of the deadline,
On Sunday we add only 24 hours.
http://jsfiddle.net/37ox54bk/7/
if (document.getElementById('countdownTimer')) {
pad = function(n, len) { // leading 0's
var s = n.toString();
return (new Array( (len - s.length + 1) ).join('0')) + s;
};
var timerRunning = setInterval(
function countDown() {
var target = 15; // 15:00hrs is the cut-off point
var now = new Date();
//Put this in a variable for convenience
var weekday = now.getDay();
if(weekday == 0){//Sunday? Add 24hrs
target += 24;
}
if(weekday == 6){//It's Saturday? Add 48hrs
target += 48;
}
//If between Monday and Friday,
//check if we're past the target hours,
//and if we are, abort.
if((weekday>=1) && (weekday<=5)){
if (now.getHours() > target) { //stop the clock
return 0;
}
}
var hrs = (target - 1) - now.getHours();
if (hrs < 0) hrs = 0;
var mins = 59 - now.getMinutes();
if (mins < 0) mins = 0;
var secs = 59 - now.getSeconds();
if (secs < 0) secs = 0;
var str = pad(hrs, 2) + ':' + pad(mins, 2) + '.<small>' + pad(secs, 2) + '</small>';
document.getElementById('countdownTimer').innerHTML = str;
}, 1000
);
}
Try this.
Instead of not doing anything when you are past the target time, I just increase the target time to point to a different day (the main difference is the if..else if statements at the beginning of the function)
function countDown() {
var now = new Date();
var target = 15; // 15:00hrs is the cut-off point
if (now.getDay() == 0) { // Sunday - use tomorrow's cutoff
target += 24;
} else if (now.getDay() == 6) { // Saturday - use cutoff 2 days from now
target += 48;
} else if (now.getHours() < target) { // missed the cutoff point. Use tomorrow instead
target += 24;
if (now.getDay() == 5) { // Friday - use Monday cutoff
target += 48;
}
}
var hrs = (target - 1) - now.getHours();
if (hrs < 0)
hrs = 0;
var mins = 59 - now.getMinutes();
if (mins < 0)
mins = 0;
var secs = 59 - now.getSeconds();
if (secs < 0)
secs = 0;
var str = pad(hrs, 2) + ':' + pad(mins, 2) + '.<small>' + pad(secs, 2) + '</small>';
document.getElementById('countdownTimer').innerHTML = str;
}, 1000);
I forked the fiddle: http://jsfiddle.net/4vhah8yt/1/
Code #sEver is good. Aj Richardson your code countdown is from new hours - is wrong.
I'd like to affter countdown hide HTML/CSS code.
Full Code: https://codepen.io/kamikstudio/pen/dyzvrQP
if (document.getElementById('countdownTimer')) {
pad = function(n, len) { // leading 0's
var s = n.toString();
return (new Array( (len - s.length + 1) ).join('0')) + s;
};
var timerRunning = setInterval(
function countDown() {
var target = 14; // 15:00hrs is the cut-off point
var now = new Date();
//Put this in a variable for convenience
var weekday = now.getDay();
if(weekday == 0){//Sunday? Add 24hrs
target += 24;
}
if(weekday == 6){//It's Saturday? Add 48hrs
target += 48;
}
//If between Monday and Friday,
//check if we're past the target hours,
//and if we are, abort.
if((weekday>=1) && (weekday<=5)){
if (now.getHours() > target) { //stop the clock
return 0;
}
}
var hrs = (target - 1) - now.getHours();
if (hrs < 0) hrs = 0;
var mins = 59 - now.getMinutes();
if (mins < 0) mins = 0;
var secs = 59 - now.getSeconds();
if (secs < 0) secs = 0;
var str = '<b>' + pad(hrs, 2) + ' </b>hours<b> ' + pad(mins, 2) + ' </b>min<b> ' + pad(secs, 2) + ' </b>sec';
document.getElementById('countdownTimer').innerHTML = str;
}, 1000
);
}

For-loop logic for dynamically creating a time based on an Index

So I've got 43 Radio buttons. When one of them is selected, it returns their index number. It's zero-based, so its 0-42. Each index corresponds to a particular time. 0 is 8:00am and 42 is 10:00pm, each index increase the time for 20 minutes. Essentially, I'm trying to generate the time I need without having to manually create if-statements for each index. Here's the broken code I have so far.
function decipherIndex(radx) {
var actime = "";
var hr = 8;
var min = 0;
var day = "am";
for (i=0;i<radx;i++) {
min = min + 20;
if (min = 60) {
hr = hr + 1;
min = 0;
}
if (hr = 13) {
hr = 0;
day = "pm";
}
}
actime = hr + ":" + min + day;
alert(actime);
}
Hopefully someone can help me work through my logic here. radx is the index that's getting passed to the function.
if (min = 60) {
hr = hr + 1;
min = 0;
}
if (hr = 13) {
hr = 0;
day = "pm";
}
You're assigning with the =, so min and hr will always be 0 and day will always be "pm". Use == or === to compare:
if (min == 60) {
hr = hr + 1;
min = 0;
}
if (hr == 13) {
hr = 0;
day = "pm";
}
However, a loop isn't necessary; all you need is a little bit of math.
function decipherIndex(i) {
var t = 60 * 8 + i * 20;
var min = t % 60;
var hr = t / 60 | 0;
return hr % 12 + ':' + (min < 10 ? '0' : '') + min + (hr >= 12 ? ' PM' : ' AM');
}

Categories

Resources