My clock won't work. Why isn't InnerHTML not updating? - javascript

Sorry if this topic is in the "annoying ones category". I recently tried to learn JS and I'm trying to make a simple clock to work. Nothing too fancy I'd say but the problem is that I can't update the values of my hours, minutes and seconds. I used .innerHTLM with a setInterval but it doesn't work. In Chrome's inspector it seems to try changing the datas but no... Any ideas guys ?
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<meta http-equiv="X-UA-Compatible" content="ie=edge">
<link rel="stylesheet" href="../css/style-clock.css">
<title>Clock</title>
</head>
<body>
<div class="container">
<div class="clock">
<span id="hours"></span>
<span id="mins"></span>
<span id="secs"></span>
</div>
</div>
<script src='../js/app-clock.js'></script>
</body>
</html>
JS:
const time = new Date();
function currentTime(){
var hour = time.getHours();
var minute = time.getMinutes();
var second = time.getSeconds();
document.getElementById("hours").innerHTML = hour;
document.getElementById("mins").innerHTML = minute;
document.getElementById("secs").innerHTML = second;
}
setInterval(currentTime,500);

You were close. Since you define time outside of the interval function, it only gets assigned once. Just move time into the currentTime() function like this:
function currentTime() {
const time = new Date();
var hour = time.getHours();
var minute = time.getMinutes();
var second = time.getSeconds();
document.getElementById("hours").innerHTML = hour;
document.getElementById("mins").innerHTML = minute;
document.getElementById("secs").innerHTML = second;
}
setInterval(currentTime, 500);
<div class="container">
<div class="clock">
<span id="hours"></span>
<span id="mins"></span>
<span id="secs"></span>
</div>
</div>

You have decelerated outside of function that is called intervals.
CodePen Example
HTML
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<meta http-equiv="X-UA-Compatible" content="ie=edge">
<link rel="stylesheet" href="../css/style-clock.css">
<title>Clock</title>
</head>
<body>
<div class="container">
<div class="clock">
<span id="hours"></span>
<span id="mins"></span>
<span id="secs"></span>
</div>
</div>
<script src='../js/app-clock.js'></script>
</body>
</html>
JS
setInterval(function(){
const time = new Date();
var hour = time.getHours();
var minute = time.getMinutes();
var second = time.getSeconds();
document.getElementById("hours").innerHTML = hour;
document.getElementById("mins").innerHTML = minute;
document.getElementById("secs").innerHTML = second;
}, 500);

The problem seems to be the positioning of the const time.
The thing is, the output of Date() will be set to const time at the beginning of the script and the currentTime() function will keep on updating the same values over and over again. So, in your case, the values were actually getting updated but since they were the same values, you couldn't make the difference.
Solution: To make it work, you need to update the value of the const time every time you need to update the value of the innerHTML. You simply need to do the following change:
JS:
function currentTime(){
const time = new Date();
var hour = time.getHours();
var minute = time.getMinutes();
var second = time.getSeconds();
document.getElementById("hours").innerHTML = hour;
document.getElementById("mins").innerHTML = minute;
document.getElementById("secs").innerHTML = second;
}
setInterval(currentTime,500);

Move the "new Date()" line into the function to set the time each interval to the current time.
function currentTime(){
const time = new Date();
var h = time.getHours();
var m = time.getMinutes();
var s = time.getSeconds();
document.getElementById("hours").innerHTML = h;
document.getElementById("mins").innerHTML = m;
document.getElementById("secs").innerHTML = s;
}
setInterval(currentTime,500);

Related

Validate Time of user input

I need to write a function to validate the time of user input from console. The format of the time is HH:mm in 24 hours time.
function isValidTime(timeString) {
var regex_time = /^\d{2}\:\d{2}$/;
if(!regex_time.test(timeString))
{
return false;
}
var hour = timeString.getHour();
var minute = timeString.getMinutes();
if ((hour > 0 && hour <= 23) && (minute > 0 && minute <= 59)) {
return true;
}
}
This is the code I have so far. When I input 5:01, the output is invalid format. When I input 17:01, it shows
node:internal/readline/emitKeypressEvents:71
throw err;
^
TypeError: timeString.getHour is not a function
Could you please help with this function, I am reading user input with readline.
I suggest you use capture groups in the regular expression... And the match method.
Match will return null if no match at all
or an array containing the full match at position 0 followed by all capture group results.
function isValidTime(timeString) {
const regex_time = /^(\d{2})\:(\d{2})$/; // Use capture groups
const timeMatches = timeString.match(regex_time)
if(!timeMatches){
return false
}
const hour = parseInt(timeMatches[1])
const minute = parseInt(timeMatches[2])
return hour >= 0 && hour <= 23 && minute >= 0 && minute <= 59
}
console.log(isValidTime("5:01")) // false
console.log(isValidTime("17:05")) // true
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<meta http-equiv="X-UA-Compatible" content="ie=edge">
<link rel="stylesheet" href="style.css">
<title>Document</title>
</head>
<body>
<div>
<input type="text" placeholder="MM" id="month">
<input type="text" placeholder="DD" id="date">
<input type="text" placeholder="YYYY" id="year">
<button>Check</button>
<h1>Result</h1>
</div>
<script src="https://cdnjs.cloudflare.com/ajax/libs/moment.js/2.24.0/moment.min.js"></script>
<script src="script.js"></script>
</body>
</html>
let btnCheck = document.querySelector('button');
let inputMonth = document.querySelector('#month');
let inputDate = document.querySelector('#date');
let inputYear = document.querySelector('#year');
let result = document.querySelector('h1');
btnCheck.addEventListener('click', (event) => {
let month = inputMonth.value;
let year = inputYear.value;
let date = inputDate.value;
// true in the end, so that our date string and date format should match exactly - in moment js it is called Strict Parsing
result.innerText = moment(`${month}/${date}/${year}`, 'MM/DD/YYYY', true).isValid();
});
Solution :
var today = new Date();
var date = today.getFullYear()+'-'+(today.getMonth()+1)+'-'+today.getDate();
var hour = today.getHours (
var minutes = today.getMinutes
Another Tip :
If you Get A Another Error you can write
var today = new Date();
var parag = document.getElementById("date")
var time = today.getHours () + ":" + today.getMinutes () + ":" + today.getSeconds();
parag.innerHTML = time

Pushing and iterating over array to display history report?

I am building a project to help kids in school learn how to read faster. I have borrowed bits of code here and there and mixed up a timer and text generator.
Now I am trying to build a function to generate a summary of the latest reading time (so that they can see progress), perhaps in the form of <ol>, I guess I need to iterate over an array, push into it and then display but none of that seems to work.
function startTime() {
var today = new Date();
var h = today.getHours();
var m = today.getMinutes();
var s = today.getSeconds();
var ampm = "";
m = checkTime(m);
if (h > 12) {
h = h - 12;
ampm = " PM";
} else if (h == 12) {
h = 12;
ampm = " AM";
} else if (h < 12) {
ampm = " AM";
} else {
ampm = "PM";
};
if (h == 0) {
h = 12;
}
document.getElementById('display').innerHTML = h + ":" + m + ampm;
var t = setTimeout(function() {
startTime()
}, 500);
}
function checkTime(i) {
if (i < 10) {
i = "0" + i
};
return i;
}
function startDate() {
var d = new Date();
var days = ["Sunday", "Monday", "Tuesday", "Wednesday", "Thursday", "Friday", "Saturday"];
document.getElementById("date").innerHTML = days[d.getDay()] + " | " + [d.getMonth() + 1] + "/" + d.getDate() + "/" + d.getFullYear();
}
var quotes = ["",
"\"Dude, suckin' at something is the first step at being sorta good at something.\"<br>- Jake <small><em>(Adventure Time)</em></small>",
"\"Either I will find a way, or I will make one.\"<br> - Philip Sidney",
"\"Our greatest weakness lies in giving up. The most certain way to succeed is always to try just one more time.\"<br>- Thomas A. Edison",
"\"You are never too old to set another goal or to dream a new dream.\"<br>- C.S Lewis",
"\"If you can dream it, you can do it.\"<br>- Walt Disney",
"\"Never give up, for that is just the place and time that the tide will turn.\"<br>- Harriet Beecher Stowe",
"\"I know where I'm going and I know the truth, and I don't have to be what you want me to be. I'm free to be what I want.\"<br>- Muhammad Ali",
"\"If you always put limit on everything you do, physical or anything else. It will spread into your work and into your life. There are no limits. There are only plateaus, and you must not stay there, you must go beyond them.\"<br>- Bruce Lee",
];
function genQuote() {
var quote = document.getElementById("quote");
var generate = document.getElementById("gen");
generate.addEventListener("click", changeText);
quote.innerHTML = quotes[0];
function changeText() {
var searchTerm = quote.innerHTML;
var index = quotes.indexOf(searchTerm) + 1;
if (index == quotes.length) index = 0;
var result = quotes[index];
quote.innerHTML = result;
return;
}
}
var startTime, endTime;
function start() {
startTime = performance.now();
};
function end() {
endTime = performance.now();
var timeDiff = endTime - startTime;
timeDiff /= 1000;
var seconds = Math.round(timeDiff);
var minutes = Math.round(seconds / 60);
document.getElementById("quote").innerHTML = ("You have read for:" + " " + minutes + " minutes" + " " + seconds + " seconds");
setTimeout(function() {
location.reload();;
}, 5000);
}
function report() {
// results = [];
// times = document.getElementById("quote").innerHTML;
// for (i=0; i <= times.length; i++) {
// results.push(i);
// return results;
// }
}
<div id="display"></div>
<div id="date"></div>
<div id="quote"></div>
<div id="get"></div>
Here is the HTML in case that help:
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<link rel="apple-touch-icon" sizes="180x180" href="/apple-touch-icon.png">
<link rel="icon" type="image/png" sizes="32x32" href="/favicon-32x32.png">
<link rel="icon" type="image/png" sizes="16x16" href="/favicon-16x16.png">
<link rel="manifest" href="/site.webmanifest">
<title>2 Cool 4 School</title>
<link rel="stylesheet" href="style.css">
<link rel="stylesheet" href="https://stackpath.bootstrapcdn.com/bootstrap/4.5.0/css/bootstrap.min.css" integrity="sha384-9aIt2nRpC12Uk9gS9baDl411NQApFmC26EwAOH8WgZl5MYYxFfc+NcPb1dKGj7Sk" crossorigin="anonymous">
<link rel="stylesheet" type="text/css" href="https://cdnjs.cloudflare.com/ajax/libs/font-awesome/4.7.0/css/font-awesome.min.css">
</head>
<body>
<body onload="startTime(); startDate()">
<div class="container">
<div id="date"></div>
<div id="display"></div>
<div id="content">
<p id="quote">"the people who are crazy enough to think they can change the world are the ones who do." <br/>- Steve Jobs</p>
</div>
</div>
<div id="b-nav">
<ul>
<button id="genone"class="btn btn-outline-primary" onclick="start()">Start</button>
<button id="gen" onclick="genQuote()">Continue reading</button>
<button id="genthree" class="btn btn-outline-success" onclick="report()">History</button>
<button id="gentwo" class="btn btn-outline-secondary" onclick="end()">End</button>
</ul>
</div>
</body>
<script src="script.js"></script>
</html>
Right now when I click Stars the timer runs, when I click End after that I am provided "you have read for: 0 minutes 4 seconds"
I would like to get a report of this something like:
you have read for: 3 minutes 30 seconds
you have read for: 2 minutes 50 seconds
you have read for: 1 minutes 40 seconds
etc Hope that helps(sorry I didnt get the snippet thing)
the biggest problem is placing "return results;" inside your loop. which means your loop never fully executes. move that outside your loop.
secondly, your report() function is just going to return a string of numbers, [0,1,2,3,4...] which is probably not what you are looking for.

stop setTime from another function with local variable

thanks for helping!
The main goal of this is Stop the timer. But It does not work.
I know that this does not work because I am calling a local variable from another function but If I declare the variable as global the setTime starts automatically and It is not what I want.
How could a solve it, or another alternative? thanks!!
This is my code:
var interval2;
function startTimef(){
var startTime = Date.now();
interval2 = setInterval(function() {
var elapsedTime = Date.now() - startTime - 5000;
document.getElementById("timer").innerHTML = (elapsedTime / 1000).toFixed(3);
}, 75);
}
function myStopFunction(interval2) {
clearInterval(interval2); // does not work because interval2 is a local variable in StartTime.
var result = document.getElementById("result");
var score = document.getElementById("timer").textContent;
if (score < -0.200) { result.innerHTML = score+" Almost there ";}
if (score < -500 && score < -0.200) { result.innerHTML = "Almost there";}
if (score > -0.200 && score < 0 ) { result.innerHTML = "No too bad mate";}
if (score > -0.100 && score < 0.200 ) { result.innerHTML = "Perfect !!!";}
if (score > 0.200 ) { result.innerHTML = "You need some work!";}
};
// Press Enter Keyboard
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<meta http-equiv="X-UA-Compatible" content="ie=edge">
<title>TimeOver</title>
</head>
<body>
<div class="main-box">
<h2>Try to Stop the timer as close as possible to cero</h2>
<p id="timer">0000</p>
<button id="stop" onclick="myStopFunction()" >Stop time</button>
<span id="result"></span>
<button id="" onclick="startTimef()" >start</button>
</div>
<script src="main.js"></script>
</body>
</html>
Try this. Removing interval2 from myStopFunction(interval2) will work.
Your first approach will not since you have 2 interval2 variables and JS will use the locally declared interval2 instead of the outer interval2.
var interval2;
function startTimef(){
var startTime = Date.now();
interval2 = setInterval(function() {
var elapsedTime = Date.now() - startTime - 5000;
document.getElementById("timer").innerHTML = (elapsedTime / 1000).toFixed(3);
}, 75);
}
function myStopFunction() {
clearInterval(interval2);
var result = document.getElementById("result");
var score = document.getElementById("timer").textContent;
if (score < -0.200) { result.innerHTML = score+" Almost there ";}
if (score < -500 && score < -0.200) { result.innerHTML = "Almost there";}
if (score > -0.200 && score < 0 ) { result.innerHTML = "No too bad mate";}
if (score > -0.100 && score < 0.200 ) { result.innerHTML = "Perfect !!!";}
if (score > 0.200 ) { result.innerHTML = "You need some work!";}
};
// Press Enter Keyboard
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<meta http-equiv="X-UA-Compatible" content="ie=edge">
<title>TimeOver</title>
</head>
<body>
<div class="main-box">
<h2>Try to Stop the timer as close as possible to cero</h2>
<p id="timer">0000</p>
<button id="stop" onclick="myStopFunction()" >Stop time</button>
<span id="result"></span>
<button id="" onclick="startTimef()" >start</button>
</div>
<script src="main.js"></script>
</body>
</html>

Display message after countdown

I have currently created a countdown timer using javascript. I want to display a message right after the countdown finishes. So, how do I display that text message if the countdown finishes?
$(function(){
var note = $('#note'),
ts = new Date(2012, 0, 1),
newYear = true;
if((new Date()) > ts){
// The new year is here! Count towards something else.
// Notice the *1000 at the end - time must be in milliseconds
ts = (new Date()).getTime() + 24*60*60*1000;
newYear = false;
}
$('#countdown').countdown({
timestamp : ts,
callback : function(days, hours, minutes, seconds){
var message = "";
message += hours + " jam ";
message += minutes + " minit" + " dan ";
message += seconds + " saat" + " lagi!";
note.html(message);
}
});
});
<!DOCTYPE html>
<html>
<head>
<meta charset="utf-8" />
<title></title>
<!-- Our CSS stylesheet file -->
<link rel="stylesheet" href="assets/css/styles.css" />
<link rel="stylesheet" href="assets/countdown/jquery.countdown.css" />
<!--[if lt IE 9]>
<script src="http://html5shiv.googlecode.com/svn/trunk/html5.js"></script>
<![endif]-->
</head>
<body>
<div id="continer">
<p><span id="timer"></span></p>
</div>
<center><img class="title" src="title.svg"></center>
<img class="icon1" src="icon1.svg">
<img class="icon2" src="icon2.svg">
<div id="countdown"></div>
<p id="note"></p>
<!-- JavaScript includes -->
<script src="http://code.jquery.com/jquery-1.7.1.min.js"></script>
<script src="assets/countdown/jquery.countdown.js"></script>
<script src="assets/js/script.js"></script>
</body>
</html>
Below is the code that I used
Well you can use setInterval, clearInterval and use a counter to keep track of seconds passed
function myFunction() {
var seconds = 0;
var finiteNumber = 300; // any number which can be calculated
var interval = setInterval(function(){
seconds++;
if(seconds === finiteNumber) {
console.log(seconds);
clearInterval(interval )
}
}, 1000);
}
You should use setTimeout as it will automatically stop on one successful execution.
function myFunction() {
var myTimeInSeconds = 600;
setTimeout(function(){
console.log(seconds);
alert('Success');
document.getElementById("demo").innerHTML = "Success Message!";
}, myTimeInSeconds);
}

How to disable a HTML submit button for a certain period of time everyday

I want to disable a button for a certain period of time everyday.
For ex: Let's say, html submit button gets disabled everyday between
11:00am and 4:00 pm.
<script type="text/javascript">
function checkButton() {
var date = new Date();
var hours = date.getHours();
var minutes = date.getMinutes();
//Hide button at 11:00 AM
if(hours == 11 && minutes == 00) {
$("#btn").hide();
}
//Show button at 04:00 PM
if(hours == 16 && minutes == 00) {
$("#btn").show();
}
}
</script>
HTML submit button reference.
<body>
<input id="btn" type="submit" value="submit" onload="checkButton()">
</body>
You shouldn't check for equality but rather check for dates being between the mentioned hours using < and > operators.
To check time between 11:00am and 4:00 pm:
let min = hours*60 + minutes;
if(min > 11*60 && min < 16*60) {
$("#btn").hide();
}else {
$("#btn").show();
}
And to check this everyday, you should put the checkButton function in a loop, such as by using setInterval function. Such as: for checking every 1 minute:
setInterval(checkButton, 60000);
My solution without Jquery:
<!DOCTYPE html>
<html>
<head></head>
<body>
<button id="btn">Click me</button>
<script>
window.onload = function() {
let btn = document.getElementById('btn');
function checkButton(){
let date = new Date();
let hours = date.getHours();
let minutes = date.getMinutes();
let min = hours*60 + minutes;
if(min > 11*60 && min < 16*60) {
//$("#btn").hide();
btn.style.display = 'none';
console.log('btn hide');
}else {
//$("#btn").show();
btn.style.display = 'block';
console.log('btn show');
}
}
setInterval(checkButton, 6000);
}
</script>
</body>
</html>
You currently just check for a point in time, but your description assumes you want to have a time range to be checked. Hence, try the following:
if(hour >= 11 && < 16) { $('#btn').hide() }
<!DOCTYPE html>
<!--
To change this license header, choose License Headers in Project Properties.
To change this template file, choose Tools | Templates
and open the template in the editor.
-->
<html>
<head>
<title>Test</title>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<script>
window.addEventListener("load", function(){
var currentTime = new Date();
var hours = currentTime.getHours();
var newButton = document.getElementById("btn");
if(hours >= 11 && hours <= 18) {
newButton.style.display = "none";
}
else {
newButton.style.display = "block";
}
}, false);
</script>
</head>
<body>
<div>Test</div>
<input type="submit" id="btn">
</body>
</html>
Use Php Date function to show the button between the hours.
<?php
$hour=date('H');
if(($hour <=11) || ($hour >=16)) {?>
<script type="text/javascript">
$("#button").show();
</script>
<?php }
?>

Categories