setInterval and 12 hour clock in javascript - javascript

I want to write a script that changes the hour displayed inside a <span> every second, starting from 8AM, and which keeps repeating like a 12 hours clock (11AM, 12PM, ..., 11PM, 12AM, 1AM, ...).
The image will change at 8AM and 8PM. At 8PM, the image will change to a sleeping face, and at 8AM the image will change back to a smile face. However, that is not a problem.
The problems are:
When I set var hour = Number(document.getElementById("time").textContent); then setInterval repeats the time without any problem. However, when I set var hour = 8 instead, and keep same code, then setInterval repeats only once. Can you let me know why it is like that and how to fix it with var hour = 8?
When the hour is repeatedly increased, I cannot make it smart to change back to AM when it reaches to 12 after passing noon (12PM). For example, the code works fine from 8AM to 11PM but when it reaches to 12, the PM does not change to AM. Can you show me how to fix it?
Lastly when I change var period = "AM" instead of using DOM getElementByID like above and keep same code, then it runs to 1PM and then changes to 2AM and never changes to PM again. Can you explain to me why it happens?
If you do not know what I am talking about, you can run my code and to understand more.
Here is the HTML:
<h2>Life goes on!</h2>
<p>The current time is : <span id = "time">8</span> <span id = "period"> AM</span></p>
<img id = "emoticon" src = "smile.gif" alt = "awake">
And here is my JavaScript code:
setInterval(function () {
var hour = Number(document.getElementById("time").textContent);
hour++;
var period = document.getElementById("period").textContent;
if (hour >= 12) {
hour = hour - 12;
period = "PM";
}
if (hour == 0) {
hour = 12;
}
document.getElementById("time").textContent = hour;
document.getElementById("period").textContent = period;
if (hour == 8 && period == "PM") {
document.getElementById("emoticon").src = "sleep.gif";
document.getElementById("emoticon").alt = "sleep";
} else if (hour == 8 && period == "AM") {
document.getElementById("emoticon").src = "smile.gif";
document.getElementById("emotion").alt = "awake";
}
}, 1000);

Let me explain the problems of your code, using the same three points you made:
Your problem about var hour = 8; is that, if you set the hour inside the setInterval callback, your hour will be set to 8 at any second. Therefore, your setInterval doesn't work only once, but it gets run infinite times setting the time always to 9. To avoid this, you can move the variable outside and make it global, setting it to 8 before starting the setInterval.
To change "PM" back to "AM" when it reaches 12PM, just add an if statement (or, better, a ternary operator, like I did in the snippet below) to check if the period is either "PM" or "AM", and behave consequently. Also, be careful with the check: if you check directly on .textContent be sure that the text inside the <span> doesn't have any trailing space: use .trim() to remove extra spaces at the beginning and at the end of the string.
This is the same problem of point 1: you should make the variable period global, and then start the setInterval.
The logic of the following script is simple:
Increase the hour by 1
If the new hour equals 12, then switch to "PM" or back to "PM"
If the new hour is greater than 12, then reset it to 1
Display hour and period
Change from smile.gif to sleep.gif when it's 8PM, and vice versa when it's 8AM.
I also made some little changes to make code easier and faster to read. Here is a working code snippet:
var hour = 8,
period = "AM";
setInterval(function() {
if (++hour >= 12) {
if (hour > 12) hour = 1;
else period = (period == "PM") ? "AM" : "PM";
}
document.getElementById("time").textContent = hour;
document.getElementById("period").textContent = period;
if (hour == 8 && period == "PM") {
document.getElementById("emoticon").src = "sleep.gif";
document.getElementById("emoticon").alt = "sleep";
} else if (hour == 8 && period == "AM") {
document.getElementById("emoticon").src = "smile.gif";
document.getElementById("emotion").alt = "awake";
}
}, 1000);
<h2>Life goes on!</h2>
<p>The current time is: <span id="time">8</span> <span id="period">AM</span></p>
<img id="emoticon" src="smile.gif" alt="awake">
Here it is, it works fine now, give it a try clicking on "Run code snippet".

Related

getHours(), show and hide

I'm currently working on my first website and have run into an issue that I just can't pass. I am using JavaScript to show and hide elements in my HTML (sounds easy enough right?) But it's not working the way it should. Even when I have an alert on the page that shows the number returned by variable 'hours', there is some issue when showing the correct information.
var today = new Date();
var hours = today.getHours();
alert(hours)
let day = document.querySelector('.day')
let night = document.querySelector('.night')
if (hours > 9 || hours < 12) {
day.style.display = "block";
night.style.display = "none";
}
else {
day.style.display = "none";
night.style.display = "block";
let blurred = document.querySelector('h1')
blurred.classList.add('blur');
}
Not to mention that eventually it should work with getUTCHours, however thought I would try this way first.
I think you specified a wrong if statement since an hour is always greater than 9 or less than 12.
Probably you meant something like if (hours >= 9 && hours <= 12)?

How to reload the page right on the first second of next day ? at midnight?

I have a dashboard page that users left open on the TV overnight.
I noticed there was a bug last night, it needs to reload as soon as it detects a new day.
Let's say today is 4/29. So, right at the first second of 4/30, I need to reload the page.
I use moment.js in my application. I'm not sure if I should load the page at midnight 12:00 PM or at 12:01 AM. I'm afraid that when I do it at 12:00 PM, it still considering the day as 4/29 making the reloading never happen and the bug 🐛 still being there.
if(moment("24:00:00", "hh:mm:ss").diff(moment(), 'seconds') == 0){
location.reload();
}
or should I do this?
if(moment().format("h") == 12){
location.reload();
}
How do I make sure that? How to verify that ?
Edit
I have this code
//====================================
// RUN every 1 mn = 60 s
//====================================
window.setInterval(function () {
getNextFeed('{{ $baby->id }}');
if(moment("24:00:00", "hh:mm:ss").diff(moment(), 'seconds') == -1){
location.reload();
}
}, 60000);
I just added it there.
No need for moment at all, here is vanilla solution that will reload page if time is 23:59, and will check if that is true every second.
You can lift an interval to few more seconds or every half minute, it will make no change and set your desired time inside if (nowHour == 23 && nowMinuts == 59)
If you need to target seconds also, then include that in if and leave interval at every second.
But if you include second cheeking then do : if (nowHour == 23 && nowMinuts == 59 && nowSecunds >= 55)
with >= to make sure it will fire with 5 second window just in case.
But i believe you are perfectly fine with just minutes.
setInterval(function() {
let nowHour = new Date().getHours()
let nowMinuts = new Date().getMinutes()
let nowSecunds = new Date().getSeconds()
console.log("Hour " + nowHour + " Minutes " + nowMinuts + " Secunds " + nowSecunds)
if (nowHour == 23 && nowMinuts == 59) {
location.reload();
}
}, 1000);
You may store the current date when page loaded, and if the date changed, it means "next day" started.
const getDate = () => moment().format('YYYY-MM-DD')
const pageLoadDate = getDate() // store current date, e.g. 2021-04-29
setInterval(() => {
if (pageLoadDate !== getDate()) {
location.reload()
}
}, 60000)

Highlight text at specific time of day

I need to highlight text at a specific time.
<style>
.highlight {
background-color:#FFFF00;
}
</style>
<span class="timer">Hello World</span>
<script>
var date = new Date();
var minute = date.getMinutes();
var hour = date.getHours();
if(
(hour >= 9 && minute >= 59) &&
(hour <= 10 && minute <= 59)
){
$('timer').addClass('highlight');
}
</script>
In the above example, it should highlight "Hello World" between 10:00 and 11:00.
This isn't working - any thoughts?
Like A. Damond said your if statement is only true if your time is either 9:59 or 10:59.
I would change your if statement to:
var date = new Date();
var minute = date.getMinutes();
var hour = date.getHours();
if ((hour === 10)) {
$('.timer').addClass('highlight');
}
.highlight {
background-color: #FFFF00;
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<span class="timer">Hello World</span>
Also you have to add the right selector in your jQuery addClass call.
$('.timer') not $('timer').
EDIT I've updated the if clause
Your if statement is equivalent to doing the same thing without parentheses. So you're checking to see if the hour is both greater than or equal to 9 and less than or equal to 10 (which will only be true if the hour is either 9 or 10) and also if the minute is both greater than or equal to 59 and less than or equal to 59 (which will only happen if the minute is exactly 59). So your if statement is only going to return true if your time is either 9:59 or 10:59.
Why not just use if (hour === 10)?
it doesn't work because in the jQuery selector you have to put a 'dot'.
$('.timer').addClass('highlight');
when you want select an id, just put
$('#timer').addClass('highlight');
As #Damon has suggested, it's simpler if you just check only the hour
(=== 10 || (=== 11 && minute === 00)) // this will include also the 11:00
Of course, if final user opens the page (at 10) and he/she never updates/reloads, the background will be always visible, or the opposite, if he opens the page at 9.
To do a job well done and working properly, you have to introduce a clock on the page and this can be a good example:
http://www.tristanwaddington.com/2010/08/javascript-clock/

Timezone specific hide/show element script

Hi first time posting here so bear with me.
I've got a live stream that I want to show on Sundays between 6am and 2pm (CEST - Central European Summer Time)
I've got the first part down but how do I make it timezone specific? Make sense?
$(document).ready(function() {
var d = new Date();
var n = d.getDay();
var hour = d.getHours();
if(n == 0 && hour >= 6 && hour < 14)
{
$(".stream").show();
} else {
$(".stream").hide();
}
} );
PS I understand this doesn't hide it completely outside of those times and that's fine. I'm just looking for a solution that works on the client side.

To change a css style depending on time of day (javascript)

im trying to write a little .js file to change a css style from display:block to display:none depending on the time of day, 08.30 to 17.00 display block and 17.00 to 08.30 display none.
Here's what i have so far:
<script language="JavaScript">
day=new Date() //..get the date
x=day.getHours() //..get the hour
if(x>=8.30 && x<17) {
document.write('<style type="text/css">#live{display:block}"></style>')
} else
if(x>=17 && x<8.30) {
document.write('<style type="text/css">#live{display:none}"></style>')
};
</script>
Do think this is good js plus not sure if using 8.30 would work plus not sure if the last ";" is needed.
Any help on this would be great thanks.
Im now trying this code but does not work
<script type="text/javascript">
$(document).ready ( function (){
var dateObj = new Date();
var hour = dateObj.getHours() * 100 + dateObj.getMinutes();
if (hour >= 1600 && hour <= 1800) {
document.getElementById('live').style.display = "none";
}
});
</script>
Date().getHours() returns an integer. For your code to work you'd have to do something like this:
var dateObj = new Date();
var hour = dateObj.getHours() * 100 + dateObj.getMinutes();
if (hour >= 830 && hour <= 1700) {
document.getElementById('your_el').style.display = "none";
}
Note that you should only use this code when the DOM is ready for manipulation.
Although, is this really what you want? JavaScript's Date gets its date and time information from the users' clock. You would probably be better off handling this on the server.
getHours() returns a whole number (0 to 23). For 8:30, you will
need to check getHours() and getMinutes() accordingly.
The last semicolon does not need to be there.
getHours() only gets you the hours number, you need to get the minutes as well
try with
x=day.getHours()+ (day.getMinutes()/100);
about the ; it is not neccessary after an if, but it's good practice to put it at the end of each code line (that would be every other line)

Categories

Resources